中央事件总线bus
-
简介:一种适用于任意组件间通信的方式
-
如何理解:将其想象成卖房中介,在租户和房东之间跑腿的人就行
-
安装:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
-
使用事件总线:
-
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) }
-
提供数据:
this.$bus.$emit('xxxx',数据)
-
-
解绑时机:在
beforeDestroy
钩子中,用$off
去解绑当前当前组件所用到的事件。 -
示例:
<div id="app"> <component-a></component-a> <br/> <component-b></component-b> <button @click="sendMessage">点我向儿子组件发送数据</button> </div> <script type="text/javascript" src="../js/vue.js"> </script> <script type="text/javascript"> var app = new Vue({ el:'#app', data:{ message:'我是根组件的数据' }, components:{ 'component-a':{ template:'<div>\ 这是来自根组件的信息:{{messageRoot}}<br/>\ 这是来自兄弟组件的信息:{{messageBrother}}\ </div>', data:function(){ return { messageRoot:'', messageBrother:'' } }, methods:{ getRootMessage:function(message){ this.messageRoot = message; }, getBrotherMessage:function(message){ this.messageBrother = message; } }, mounted:function(){ // 给bus绑定自定义事件,回调留在自身,说明我想获得数据 this.$bus.$on('RootMessage', this.getRootMessage); this.$bus.$on('BrotherMessage', this.getBrotherMessage); } }, 'component-b':{ template:'<div>\ <button @click="sendMessage">点我向兄弟组件发送数据</button>\ </div>', data:function(){ return { message:'我是兄弟组件的数据' } }, methods:{ sendMessage(){ this.$bus.$emit('BrotherMessage', this.message); } } } }, methods:{ sendMessage(){ this.$bus.$emit('RootMessage', this.message); } }, beforeCreate(){ Vue.prototype.$bus = this; // 安装中央事件总线bus } }) </script>