全局事件总线
全局事件总线是一种组件间的通信方式,相比于props,它可以在任意组件间进行通信。
使用方法
首先要在vm实例对象上设置全局事件总线
在main.js中
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus=this//安装全局总线
}
}).$mount('#app')
之所以这样做的原因是:在vm的实例对象上,所有组件都可以访问到并且可以使用其方法,这一点尤为重要。 我们举一个例子 有一个组件App,
<template>
<div>
<h1>{{message}}</h1>
<SchoolInfo/>
</div>
</template>
<script>
import SchoolInfo from './components/SchoolInfo.vue'
export default {
name:'App',
data(){
return{
message:'app',
}
},
components:{
SchoolInfo
},
methods:{
getStudentdata(name,age,sex){
console.log(name);
console.log(age);
console.log(sex);
}
},
mounted(){
//绑定事件 getStudentdata是我们绑定的事件名 this.getStudentdata是我们指定的回调函数
this.$bus.$on('getStudentdata',this.getStudentdata)
},
beforeDestroy(){
//解绑事件 通常情况下,在组件卸载前 要将绑定的事件 解绑
this.$bus.$off('getStudentdata')
}
}
</script>
<style>
*{
margin: 0;
padding: 0;
}
</style>
App的孙组件 StudentInfo
<div class="student">
<h3>学生姓名:{{name}}</h3>
<h3>学生年龄:{{age}}</h3>
<h3>学生性别:{{sex}}</h3>
<button @click="send(name,age,sex)">发送数据</button>
</div>
</template>
<script>
export default {
name:'StudentInfo',
data(){
return {
name:'xxx',
age:'22',
sex:'男'
}
},
methods:{
send(name,age,sex){
this.$bus.$emit('getStudentdata',name,age,sex)
}
}
}
</script>
<style>
.student{
margin: 5px;
background-color: cornflowerblue;
}
</style>
我们点击发送按钮 ,就会触发send()函数,当然里面有参数,这时,就会触发里面我们提前绑定好的getStudentdata事件。在getStudentdata中对数据进行输出