03-计数器案例

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计数器</title>
</head>
<body>
<div id="app">
    <h2>{
    
    {
    
    counter}}</h2>
    <button v-on:click="counter++">+</button>
    <button v-on:click="counter--">-</button>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
    
    
        el: '#app',
        data: {
    
    
            counter: 0
        },
    })
</script>
</html>

以上情况不推荐使用

示例2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计数器</title>
</head>
<body>
<div id="app">
    <h2>{
    
    {
    
    counter}}</h2>
    <button v-on:click=add>+</button>
    <button @click="sub">-</button>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
    
    
        el: '#app',
        data: {
    
    
            counter: 0
        },
        methods: {
    
    
            add: function () {
    
    
                console.log('+')
                this.counter++
            },
            sub: function () {
    
    
                console.log('-')
                this.counter--
            }
        }
    })
</script>
</html>

推荐使用,其中v-on:等效于@,@是v-on的语法糖

猜你喜欢

转载自blog.csdn.net/plan_jok/article/details/112855405