全局事件组件的优点:它可以实现任意组件之间的通信。主要是利用$bus来实现的。
直接说用法:
1.安装全局事件总线,打开min.js,在new Vue的时候,使用beforeCreate钩子,在vue原型上面挂载全局事件总线。
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this //在原型上面挂载全局事件总线
}
}).$mount('#app')
2.使用事件总线
假设有两个组件,分别为A组件,B组件。B组件给A组件传递数据,A组件接收B组件的数据。
接收数据:A组件要接收数据,则在A组件中给$bus绑定自定义事件,事件的回调在A组件自身。
组件A接收代码:
<template>
<div class="about">
<h1>我是about组件</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
</div>
</template>
<script>
export default {
data(){
return {
name:'',
age:''
}
},
methods:{
getData(name,age){
this.name = name;
this.age = age
}
},
mounted(){
//通过$bus来执行$on,以此来接收组件发出的事件,并调用getData()函数,里面的name,age参数就是过来的数据
this.$bus.$on('Data',this.getData)
}
}
</script>
B组件传递数据代码:
<template>
<div class="home">
<hr>
<h1>我是home组件</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="setData">点击发送数据</button>
</div>
</template>
<script>
export default {
name: 'Home',
data(){
return {
name:'孙悟空',
age:99
}
},
methods:{
setData(){
//通过点击事件触发此方法,通过$bus来执行$emit,以此来发出事件
this.$bus.$emit('Data',this.name,this.age)
}
}
}
</script>
未传值前效果:
传值后的效果:
需要注意的是,在使用完之后。最好在beforeDestroy这个钩子中,用$off去解绑一下当前组件所用到的事件。
代码:
<template>
<div class="about">
<h1>我是about组件</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
</div>
</template>
<script>
export default {
data(){
return {
name:'',
age:''
}
},
methods:{
getData(name,age){
this.name = name;
this.age = age
}
},
mounted(){
//通过$bus来执行$on,以此来接收组件发出的事件,并调用getData()函数,里面的name,age参数就是过来的数据
this.$bus.$on('Data',this.getData)
},
beforeDestroy(){
this.$bus.$off('Data')
}
}
</script>
以上就是Vue任意组件通信的一种方法。