vue3 如何bus事件怎么写
时间: 2023-07-18 21:41:32 浏览: 35
在 Vue 3 中,可以使用 `createApp` 方法创建一个 Vue 实例,然后在该实例中通过 `provide` 和 `inject` 方法创建一个全局的事件总线,从而实现类似于 Vue 2 中 `$emit` 和 `$on` 方法的功能。
下面是一个示例代码:
```javascript
// 创建一个 Vue 实例
const app = Vue.createApp({});
// 创建一个空的事件总线对象
const eventBus = {};
// 在 Vue 实例中通过 provide 方法提供事件总线对象
app.provide('eventBus', eventBus);
// 在组件中通过 inject 方法注入事件总线对象
app.component('example-component', {
inject: ['eventBus'],
mounted() {
// 发送事件
this.eventBus.emit('example-event', 'Hello, world!');
// 监听事件
this.eventBus.on('example-event', data => {
console.log(data); // 输出:Hello, world!
});
},
});
// 挂载 Vue 实例
app.mount('#app');
```
在上面的示例代码中,我们首先通过 `createApp` 方法创建了一个 Vue 实例,并创建了一个空的事件总线对象。然后,在 Vue 实例中通过 `provide` 方法将事件总线对象提供给所有子组件。
在子组件中,我们通过 `inject` 方法注入事件总线对象,并在 `mounted` 钩子中通过 `emit` 方法发送一个名为 `example-event` 的事件,并附带一个数据 `Hello, world!`。同时,我们还通过 `on` 方法监听了 `example-event` 事件,并在回调函数中输出了接收到的数据。