vue的事件绑定

v-on事件绑定指令,用来辅助程序员为DOM元素绑定事件监听

 原生DOM对象有onclick、oninput、onkeyup等原生事件,替换为vue的事件绑定形式后为v-on:click、v-on:input、v-on:keyup

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
    <button v-on:click="greet">Greet</button>
    <p>{{ num }}</p>
    <button v-on:click="addCount">+1</button>


</div>
<script>
    var app = new Vue({
        el:"#app",
        data: {
            name: "vue.js",
            num: 0
        },
        methods:{  //v-on绑定的事件处理函数需要在methods中声明
            greet: function (event){
                alert('hello'+ this.name+'!')
                if(event){
                    alert(event.target.tagName)
                }
            },
            addCount: function (num){ //事件处理函数的名字
                // this表示当前new出来的vm实例对象
                // 通过this可以访问到data中的数据
                this.num +=1
            }
        }
    })
</script>
</body>
</html>

 

posted @ 2021-12-07 15:53  fat_girl_spring  阅读(321)  评论(0编辑  收藏  举报