• 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>
  • 相关阅读:
    分享动态生成文字图片解决方案
    文本框的回车添加事件
    最小化到系统托盘代码
    匹配所有html标记 正则
    根据字体文件创建字体
    获取或设置当用户按 Enter 键时所单击的窗体上的按钮。
    c#webBrowser 实现自动填入选择下拉列表
    [08] Docker_2
    [07] Docker_1
    查了一下平板电视的价格行情
  • 原文地址:https://www.cnblogs.com/mofei1999/p/12819316.html
Copyright © 2020-2023  润新知