<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue 实例事件</title> <script type="text/javascript" src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script> </head> <body> <h1>Vue 实例事件</h1> <hr> <div> <p> {{num}} </p> <p><button @click="add">add</button></p> </div> <p><button οnclick="reduce()">reduce</button></p> <p><button οnclick="reduceonce()">reduceonce</button></p> <p><button οnclick="off()">关闭事件</button></p> </body> </html> <script> var app = new Vue({ el:'#app', data:{ num:1 }, methods:{ add:function(){ this.num++ } }, }) //在构造器 on 一直调用 once只能调用一次 app.$on('reduce',function(){ this.num--; console.log('执行了reduce方法') }) app.$once('reduceonce',function(){ this.num--; console.log('执行了reduceonce方法') }) function reduce(){ //emit 触发当前实例上的事件 app.$emit('reduce'); } function reduceonce(){ app.$emit('reduceonce'); } // $off 关闭事件 function off(){ app.$off('reduce'); console.log('关闭了reduce') } </script>
运行结果: