vue

1.$on(在构造器外部添加事件)

2.$once(执行一次的事件)

3.$off(关闭事件)

4.$emit(事件调用)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Vue入门之Helloworld</title>
 7     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 8 </head>
 9 
10 <body>
11     <div id="app">
12         <div>数字:{{count}}</div>
13         <button onclick="reduce()">on调用</button>
14         <button onclick="reduceOnce()">once调用</button>
15         <button onclick="off()">off调用</button>
16     </div>
17 
18     <script type="text/javascript">
19         var app = new Vue({
20             el: '#app',
21             data: {
22                 count: 1
23             }
24         })
25 
26 
27         // 官方示例(vm指的是vue绑定,也是是上述所指的app.$on):
28         // vm.$on('test', function (msg) {
29         //     console.log(msg)
30         // })
31         // vm.$emit('test', 'hi')
32         // => "hi"
33 
34 
35 
36         // $on 在构造器外部添加事件
37         app.$on('reduce', function () {
38             console.log('执行了reduce()');
39             this.count--;
40         });
41         // 调用
42         function reduce() {
43             // 事件调用
44             console.log('emit事件调用');
45             app.$emit('reduce');
46         }
47 
48         // $once执行一次的事件
49         app.$once('reduceOnce', function () {
50             console.log('只执行一次的方法');
51             this.count--;
52         });
53 
54         // 调用
55         function reduceOnce() {
56             app.$emit('reduceOnce');
57         }
58 
59         // 关闭事件
60         function off() {
61             console.log('关闭事件');
62             app.$off('reduce');
63         }
64     </script>
65 </body>
66 
67 </html>

 

原文地址:https://www.cnblogs.com/cisum/p/9617393.html