一、vue2 中使用事件總線垛耳,實現(xiàn)兄弟組件傳值
- 在 main.js 中定義事件總線
new Vue({
router,
store,
render: (h) => h(App),
beforeCreate() {
Vue.prototype.$bus = this;
},
}).$mount("#app");
- 在組件A中監(jiān)聽事件
mounted() {
this.$bus.$on("getUserInfo", (data) => {console.log(data)});
},
destroyed() {
this.$bus.$off("getUserInfo");
},
- 在組件B中觸發(fā)事件
mounted() {
setTimeout(() => {
this.$bus.$emit("getUserInfo", { username: "alias", password: "123456" });
}, 1000);
},
二栅屏、vue3 中使用事件總線,實現(xiàn)兄弟組件傳值
在vue3中
$on堂鲜、$off栈雳、$once
被移除,$emit
保留
解決方案:使用第三方庫 mitt 代替$on缔莲、$off哥纫、$once
實現(xiàn)兄弟組件傳值
- 安裝 mitt
npm install mitt -S
- 在 main.js 中把事件總線綁定到全局屬性上
import mitt from 'mitt'
app.config.globalProperties.Bus = mitt()
- 在組件A中監(jiān)聽事件
<script setup>
import { getCurrentInstance, onUnmounted } from 'vue'
const { $bus } = getCurrentInstance().appContext.config.globalProperties
$bus.on('getUserInfo', (data) => console.log(data))
onUnmounted(() => {
$bus.off('getUserInfo')
})
</script>
- 在組件B中觸發(fā)事件
import { getCurrentInstance, onMounted } from 'vue';
const { $bus } = getCurrentInstance().appContext.config.globalProperties
onMounted(()=>{
setTimeout(() => {
$bus.emit("getUserInfo", { username: "alias", password: "123456" });
}, 1000);
})
- 官方示例
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten