解决问题
- 父子组件之间的通信问题
- Vue开发中
$emit、$on和$off
的用法 - eventBus遇到数据不更新的问题
1、Vue开发中 $emit、$on、$once和$off
的用法
$emit、$on、$off、$once
$emit、$on
:$emit触发当前实例上的自定义事件(并将附加参数都传给监听器回调),使用 $on 监听该事件并调用回调函数。这两个事件方法可以结合props 属性实现父子组件双向传参
$once
:$once(eventName,callback) 监听一个自定义事件,但是只触发一次,在第一次触发之后移除监听器
$off
:$off([eventName,callback]) 用来移除自定义事件监听器。如果没有提供参数,则移除所有的事件监听器;如果只提供了事件,则移除该事件所有的监听器;如果同时提供了事件与回调,则只移除这个回调的监听器。
父组件
<template>
<div>
<div>父组件{
{toCity}}</div>
<action-bar @showchangeName="handleChange" :sendData="bartitle"></action-bar>
</div>
<template>
<script>
import ActionBar from "@/components/actionBar.vue";
export default {
components: {
ActionBar },
data () {
return {
bartitle:"展开"
}
},
methods:{
handleChange(data){
//触发子组件的事件
this.bartitle= data.name;//改变了父组件的值
console.log('bartitle:'+this.bartitle)
}
}
}
</script>
子组件
<template>
<div class="container">
<h3>这是接收到的父组件传过来的参数:{
{ParentData}}</h3>
<br/><button @click='sendToParent(`隐藏`)'>点击此处将‘隐藏’发送到父组件</button>
</div>
</template>
<script>
export default {
props:['ParentData'], // 用来接收父组件传给子组件的数据
methods:{
sendToParent(val) {
let data = {
name: val
};
this.$emit('showchangeName',data);//sendToParent方法触发showchangeName事件,并传参到监听方法
}
}
}
</script>
2、 Vue开发中 $emit、$on和$off
的用法
新建一个eventBus.js文件:两个页面没有任何引入和被引入关系,实现数据通信
EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件,但也就是太方便所以若使用不慎,就会造成难以维护的“灾难”,因此才需要更完善的Vuex作为状态管理中心,将通知的概念上升到共享状态层次。
// eventBus.js
import Vue from 'vue';
export default new Vue();
main.js全局引用
import Vue from 'vue'
import bus from '@/assets/eventBus';
Vue.prototype.bus = bus;
componentA:$on
created(){
//这个值与组件B的bus.$emit(第一个参数相同)
this.bus.$on("change-theme", (e) => {
this.isShow= e // 页面一加载的时候触发得到传过来的值
});
}
componentB:$emit
<template>
<div>
<!--当点击的时候就会传替参数true 过去子组件就会显示 -->
<el-button @click="hanbdleClick">点击传替信息</el-button>
<componentA></componentA>
</div>
</template>
<script>
import componentA "./componentA";
export default {
methods:{
hanbdleClick(){
this.bus.$emit("change-theme",true) // 使用$emit自定义事件把数据带过去
},
},
components:{
componentA }
}
</script>
<style scoped>
</style>
$off
:意思就是移除绑定元素
componentB事件销毁
beforeDestroy() {
this.bus.$off("change-theme");
},
3、eventBus遇到数据不更新的问题
在问题2中,可能会存在eventBus遇到数据不更新的问题
注意
在
$emit
时,必须已经$on
,否则将无法监听到事件。
所以正确的写法应该是在需要接收值的组件的created生命周期函数里写$on,在需要往外传值的组件的destroyed生命周期函数函数里
destroyed(){
this.bus.$emit('change-theme',data)
}