1

Vue中EventBus(事件总线)的基本用法

 1 year ago
source link: https://www.fly63.com/article/detial/12189
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vue中EventBus(事件总线)的基本用法

更新日期: 2022-09-30阅读: 7标签: 事件分享

扫一扫分享

vue组件中最常见的数据传递就是父子组件之间的传递,父组件可以通过 props 向下传数据给子组件,子组件可以通过 $emit 事件携带数据给父组件。然而当两个页面没有任关系,该如何通信?这就引出了 EventBus ( 事件总线 ) 这个概念

方法一:新建文件

首先需要初始化一个 EventBus,并且向外共享一个 Vue 的实例对象
新建一个 js 文件,比如:EventBus.js

// src/utils/EventBus.js 文件
import Vue from 'vue'

// 向外共享 Vue 的实例对象
export default new Vue()

方法二:挂载在 Vue 的原型上

在 main.js 中初始化 EventBus

// src/main.js

Vue.prototype.$EventBus = new Vue()
// a.vue

// 导入 EventBus
import EventBus from '@/utils/EventBus'

// 通过调用 bus.$emit('自定义事件', 数据) 触发自定义事件发送数据
EventBus.$emit('share', this.a_data);
// b.vue

// 导入 EventBus
import EventBus from '@/utils/EventBus'

// 通过调用 $on('自定义事件', 事件处理函数) 注册自定义事件接收数据
// 其中,value 即为接收的数据
EventBus.$on('share', value => {
this.b_data = value;
})

在组件离开,也就是被销毁前,需要将该监听事件给移除,以免下次再重复创建监听

// b.vue

// 移除监听事件 "share"
EventBus.$off('share')

完整代码

utils/EventBus.js

import Vue from 'vue'

// 向外共享 Vue 的实例对象
export default new Vue()



A 组件代码

<template>
<div>
<button @click="send">点我发送消息</button>
</div>
</template>

<script>
import EventBus from '@/utils/EventBus'

export default {
data:()=>({
a_data: 'message'
}),
methods: {
send () {
EventBus.$emit('share', this.a_data);
}
}
}
</script>



B 组件代码

<template>
<div>
<h1>{{ b_data }}</h1>
</div>
</template>

<script>
import EventBus from '@/utils/EventBus'

export default {
data: () => ({
b_data: null
}),
created () {
EventBus.$on('share', value => {
// 将 A 组件传递过来的数据保存到 B 组件
this.b_data = value;
})
},
beforeDestroy() {
// 移除监听事件 "share"
EventBus.$off('share')
}
}
</script>

来源:https://www.cnblogs.com/bkzj/p/16743584.html

链接: https://www.fly63.com/article/detial/12189


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK