vue2.0中的变化

vue.js2.0中废弃了event选项,所有自定义事件都需要通过$emit,$on,$off函数来进行触发、监听和取消监听。

废弃了$dispatch和$broadcast方法;

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1">
 6     <meta name="viewport" content="width=device-width,initial-scale=1">
 7     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 8     <!--<script src="../js/vue.js"></script>-->
 9     <title>Title</title>
10 </head>
11 <body>
12     <!--集中式的事件管理机制来处理组件间的通信-->
13     <div id="app">
14         <comp-a></comp-a>
15         <comp-b></comp-b>
16     </div>
17 
18     <!--keep-alive不再是动态组件component标签中的属性,而成为了单独的标签-->
19     <keep-alive>
20         <component :is="currentView"></component>
21     </keep-alive>
22 
23     <!--确保子组件只激活一个-->
24     <keep-alive>
25         <comp-a v-if="active"></comp-a>
26         <comp-b v-else></comp-b>
27     </keep-alive>
28 
29     <!--slot不再支持多个slot属性的DOM插入到对应的slot标签中,一个slot只被使用一次-->
30         <div slot="modal-header" class="modal-header">Title1</div>
31         <div slot="modal-header" class="modal-header">Title2</div>
32         <!--子组件-->
33         <slot name="modal-header"></slot>
34     <!--在vue2.0中第二个model-header会被忽略,slot标签不再保存自身的属性与样式,均由父元素或被插入的元素提供样式和属性-->
35 
36     <!--子组件索引不再是一个指令-->
37     <comp ref="first"></comp><!--vue2.0-->
38     <comp v-ref="first"></comp><!--vue1.0-->
39     <script>
40         // 定义一个空的vue实例, bus实例可抽象成一个集中式的事件处理器,供所有的组件使用
41         let bus = new Vue();
42 
43         let vm = new Vue({
44             el: '#app',
45             components: {
46                 compA: {
47                     template: '<div><input type="text" v-model="name" /><button @click="create">添加</button></div>',
48                     data: function () {
49                         return {
50                             name: ''
51                         }
52                     },
53                     methods: {
54                         create: function () {
55                             bus.$emit('create',{name: this.name });
56                             this.name = '';
57                         }
58                     }
59                 },
60                 compB: {
61                     template: '<ul><li v-for="item in items">{{ item.name }}</li></ul>',
62                     data: function () {
63                         return {
64                             items: []
65                         }
66                     },
67                     // mounted 为vue2.0中新的生命周期函数
68                     mounted() {
69                         let that = this;
70                         bus.$on('create',function (data) {
71                             that.items.push(data);
72                         });
73                     }
74                 }
75             }
76         });
77 
78     </script>
79 </body>
80 </html>
原文地址:https://www.cnblogs.com/wuting/p/8885771.html