山东省建设机械协会网站,wordpress 主题哪里买,硬盘做网站空间,wordpress数据库使用全局事件总线(GlobalEventBus)
一种可以在任意组件通信的方式#xff0c;本质上就是一个对象#xff0c;它必须满足以下条件
所有的组件对象都必须能看见他这个对象必须能够使用$ on $ emit $ off方法取绑定、触发和解绑事件
使用步骤
定义全局事件总线
//创建VUE
new V…全局事件总线(GlobalEventBus)
一种可以在任意组件通信的方式本质上就是一个对象它必须满足以下条件
所有的组件对象都必须能看见他这个对象必须能够使用$ on $ emit $ off方法取绑定、触发和解绑事件
使用步骤
定义全局事件总线
//创建VUE
new Vue({el:#app,render:h h(App),beforeCreate(){Vue.prototype.$busthis //安装全局事件总线},})使用事件总线 a.接收数据A组件想接收数据则在A组件中给$bus 绑定自定义事件事件的回调留在A组件自身
export default{methods(){demo(data){...}}...mounted(){this.$bus.$on(xxx,this.demo)}
}b.提供数据this.$bus.$emit(xxx,data) 3. 最好在beforeDestroy钩子中用**$off()**去解绑当前组件所用到的事件。
src/main.js
//引入vue
import Vue from vue
//引入APP.vue
import App from ./App.vue//关闭Vue的生产提示
Vue.config.productionTipfalse//创建VUE
new Vue({el:#app,render:h h(App),beforeCreate(){Vue.prototype.$busthis //安装全局事件总线},})
src/App.vue
templatediv classapph1{{msg}}/h1School/SchoolStudent/Student/div
/templatescriptimport Student from ./components/Studentimport School from ./components/Schoolexport default {name:App,components:{School,Student},data() {return {msg:你好啊}}}
/scriptstyle scoped.app{background-color: gray;padding: 5px;}
/style
src/compoents/School.vue
templatediv classschoolh2学校名称{{name}}/h2h2学校地址{{address}}/h2/div
/templatescriptexport default {name:School,data() {return {name:尚硅谷,address:北京,}},mounted() {// console.log(School,this)this.$bus.$on(hello,(data){console.log(我是School组件收到了数据,data)})},beforeDestroy() {this.$bus.$off(hello)},}
/scriptstyle scoped.school{background-color: skyblue;padding: 5px;}
/stylesrc/compoents/Student.vue
templatediv classstudenth2学生姓名{{name}}/h2h2学生性别{{sex}}/h2button clicksendStudentName把学生名给School组件/button/div
/templatescriptexport default {name:Student,data() {return {name:张三,sex:男}},mounted() {// console.log(Student,this.x)},methods: {sendStudentName(){this.$bus.$emit(hello,this.name)}},}
/scriptstyle scoped.student{background-color: pink;padding: 5px;margin-top: 30px;}
/style