例子说明:主持人组件发布命令,1个门卫组件、2个参会者组件接收命令。
效果如下图所示:
代码比较简单,不多解释了。
<!DOCTYPE html> <!-- 作者:wallimn 博客:http://wallimn.iteye.com 时间:2017-11-22 --> <html> <head> <meta charset="utf-8"> <title>vue事件总线示例</title> <script type="text/javascript" src="../lib/vue.js"></script> </head> <body> <div id="meetingHost"> 主持人命令:<select v-model="command"> <option value="开会">开会</option> <option value="休息">休息</option> <option value="散会">散会</option> </select> <button type="button" @click="sendCommand">发布命令</button> </div> <hr> <div id="guard"> 门卫收到命令:{{commandOfHost}} </div> <div id="guest"> <meeting-guest name="张三"></meeting-guest> <meeting-guest name="李四"></meeting-guest> </div> <script type="text/javascript"> var Bus = new Vue();//事件总线 //主持人 var vueHost = new Vue({ el:'#meetingHost', data:function(){ return { command:'' }; }, methods:{ sendCommand:function(){ Bus.$emit('hostCommand',this.command); } } }); //自定义组件,参会者 Vue.component('meeting-guest', { template: '<div>{{name}}收到命令:{{ commandOfHost }}</div>', props:['name'], data: function(){ return { commandOfHost: '' }; }, created:function(){ var self = this; Bus.$on('hostCommand',function(command){ self.commandOfHost = command; }); } }); var vueGuest = new Vue({el:'#guest'}); //门卫 var vueGuard = new Vue({ el:"#guard", data:function(){ return { commandOfHost:'' }; }, created:function(){ var self = this; Bus.$on('hostCommand',function(command){ self.commandOfHost = command; }); } }); </script> </body> </html>