自定义事件触发机制
$emit、$dispatch、$broadcast用法:
1 <!DOCTYPE html> 2 <html> 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 <title>自定义事件触发机制</title> 8 </head> 9 <body> 10 <!--模板--> 11 <div id="app"> 12 <input type="text" v-model="content"> 13 <button @click="addTodo">添加</button> 14 <button @click="broadcast">广播</button> 15 <child-todo name="one"></child-todo> 16 <child-todo name="two"></child-todo> 17 <ul> 18 <li v-for="value in todo"> 19 {{ value }} 20 </li> 21 </ul> 22 </div> 23 <script src="../js/vue.js"></script> 24 <script> 25 // 子组件 26 Vue.component('child-todo',{ 27 props: ['name'], 28 data: function () { 29 return { 30 content: '' 31 } 32 }, 33 template:'<div>Child {{name}}<input type="text" v-model="content" />' + 34 '<button @click="add">添加</button></div>', 35 methods: { 36 add: function () { 37 //向上冒泡,触发父组件中定义好的add事件 38 this.$dispatch('add','Child '+this.name+': '+this.content); 39 this.content = ''; 40 } 41 }, 42 events:{ 43 'to-child':function (msg) { 44 //向上冒泡,触发父组件中定义好的add事件 45 this.$dispatch('add','Child '+this.name+': '+msg); 46 } 47 } 48 }); 49 // 根实例 50 var vm = new Vue({ 51 el:'#app', 52 data: { 53 todo:[], 54 content:'' 55 }, 56 methods: { 57 addTodo: function () { 58 // 触发自己实例中的事件 59 this.$emit('add','parent: '+this.content); 60 this.content = ''; 61 }, 62 broadcast: function () { 63 // 将事件广播,使两个子组件实例都触发to-child事件 64 this.$broadcast('to-child',this.content); 65 this.content = ''; 66 } 67 }, 68 events: { 69 'add': function (msg) { 70 this.todo.push(msg); 71 } 72 } 73 }); 74 75 </script> 76 77 </body> 78 </html>