01-Vue初学习--计数器案例

1. 业务要求

  (1)点击 + 号,计数器 +  1

  (2)点击 - 号,计数器 - 1

2. 不考虑逻辑功能时,编写 html 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<!-- 数据与界面分离-->
<div id="app">
     <h2>当前计数:{{counter}}</h2>
    <button>+</button>
    <button>-</button>
</div>
<script src="../js/vue.js"></script>
<script>
    //点击 + 计数器 + 1
    //点击 - 计数器 -1
    const app = new Vue({
        el: '#app',//用于挂载要管理的元素
        data:{//定义数据
            counter : 0
        }
    })
</script>
</body>
</html>

3. Vue的点击事件:   v-on:click

<button v-on:click="counter++">+</button>
<button v-on:click="counter--">-</button>

4. 将  "counter++"  "counter--"封装为函数

    <button v-on:click="add">+</button>
    <button v-on:click="sub">-</button>
...
const app = new Vue({
        el: '#app',//用于挂载要管理的元素
        data:{//定义数据
            counter : 0
        },
        methods:{//定义方法
            add : function(){
                this.counter++;
                console.log("add被执行")//控制台打印
            },
            sub : function(){
                this.counter--;
                console.log("sub被执行")
            }
        }
    })

5. 源代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<!-- 数据与界面分离-->
<div id="app">
    <h2>当前计数:{{counter}}</h2>
    <!-- 如果点击的同时 还想打印一句话通知修改了,那就比较麻烦 
    <button v-on:click="counter++">+</button>
    <button v-on:click="counter--">-</button>-->
    <!-- click 指令 -->
    <button v-on:click="add">+</button>
    <button v-on:click="sub">-</button>
</div>
<script src="../js/vue.js"></script>
<script>
    //点击 + 计数器 + 1
    //点击 - 计数器 -1
    const app = new Vue({
        el: '#app',//用于挂载要管理的元素
        data:{//定义数据
            counter : 0
        },
        methods:{//定义方法
            add : function(){
                this.counter++;
                console.log("add被执行")
            },
            sub : function(){
                this.counter--;
                console.log("sub被执行")
            }
        }
    })
</script>
</body>
</html>

 

posted @ 2020-05-02 19:55  莫飞的博客  阅读(207)  评论(0编辑  收藏  举报