VUE装载全局事件总线

391次阅读
没有评论
VUE 装载全局事件总线

在 vue 中,父组件传值给子组件可以使用 Prop 去接收值,比较方便

但是子组件往父组件中传值就相对麻烦

兄弟组件之间传值就更麻烦

vue 中全局事件组件,相当于每个组件去和 Vue 的实例对象去交流

免去了 Prop 的传值过程,相对比较好用

首先在 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')

在 app.vue 中注册两个组件

<template>
  <div>
    <school/>
    <student/>
  </div>
</template>

<script>
import School from './components/SchoolCom.vue'
import Student from './components/StudentCom.vue'
export default {
  name: 'App',
  components: {School,Student}
}
</script>

在 stduent.vue 中先挂载上自定义事件,用于随时接收数据

这里使用生命周期函数 mounted 时挂载事件,beforeDestroy 的是时候去卸载事件

<template>
    <div>
        <h1>{{name}}</h1>
        <h2 v-if="msg"> 学校发送的消息:{{msg}}</h2>
    </div>
</template>

<script>
    export default {
        name:'studentCom',
        data(){
            return {
                name:"小明",
                msg:""
            }
        },
        mounted(){this.$bus.$on("sendMsg",(msg)=>{console.log(msg)
                this.msg = msg
            })
        },
        beforeDestroy(){this.$bus.$off("sendMsg")
        }
    }
</script>

接收端有了,就要写一个触发端去传递数据

<template>
    <div>
        <h1>{{name}}</h1>
        <button @click="sendMsgToStudent"> 点击向学生发送消息 </button>
    </div>
</template>

<script>
    export default {
        name: "schoolCom",
        data(){
            return {name: "小学"}
        },
        methods:{sendMsgToStudent(){this.$bus.$emit("sendMsg","明天上学")
            }
        }
    }
</script>

最终效果如图:小明很不幸,明天得上学

VUE 装载全局事件总线
正文完
 
评论(没有评论)