Vue全局事件總線你了解嗎
全局事件總線,是組件間的一種通信方式,適用于任何組件間通信。
看下面具體的例子。
父組件:App
<template> <div class="app"> <Company/> <Employee/> </div> </template> <script> import Company from "./components/Company.vue"; import Employee from "./components/Employee.vue"; export default { components:{ Company, Employee } } </script> <style> .app{ background: gray; padding: 5px; } .btn{ margin-left:10px; line-height: 30px; background: ivory; border-radius: 5px; } </style>
子組件:Company和Employee
<template> <div class="company"> <h2>公司名稱:{{name}}</h2> <h2>公司地址:{{address}}</h2> <button @click="sendMessage">點我發(fā)送</button> </div> </template> <script> export default { name:"Company", data(){ return { name:"五哈技術有限公司", address:"上海寶山" } }, methods:{ sendMessage(){ console.log("Company組件發(fā)送數(shù)據(jù):",this.name); this.$bus.$emit("demo",this.name); } } } </script> <style scoped> .company{ background: orange; background-clip: content-box; padding: 10px; } </style>
<template> <div class="employee"> <h2>員工姓名:{{name}}</h2> <h2>員工年齡:{{age}}</h2> </div> </template> <script> export default { name:"Employee", data(){ return { name:"張三", age:25 } }, mounted(){ this.$bus.$on("demo",(data) => { console.log("Employee組件監(jiān)聽demo,接收數(shù)據(jù):",data); }) }, beforeDestroy() { this.$bus.$off("demo"); } } </script> <style scoped> .employee{ background: skyblue; background-clip: content-box; padding: 10px; } </style>
入口文件:main.js
import Vue from 'vue'; import App from './App.vue'; Vue.config.productionTip = false; new Vue({ el:"#app", render: h => h(App), beforeCreate(){ Vue.prototype.$bus = this; } })
父組件App,子組件Company
和Employee
子組件Company和Employee之間通過全局數(shù)據(jù)總線進行數(shù)據(jù)傳遞。
在main.js中,定義了全局事件總線:$bus
。
$bus
定義在Vue.prototype
,因此$bus
對所有組件可見,即所有組件可通過this.$bus
訪問。
$bus
被賦值為this
,即vm實例,因此$bus
擁有vm實例上的所有屬性和方法,如$emit
、$on
、$off
等。
new Vue({ beforeCreate(){ Vue.prototype.$bus = this; } })
使用全局事件總線
$bus.$on
,監(jiān)聽事件。Employee組件中定義了監(jiān)聽事件,監(jiān)聽demo事件;
$bus.$emit
,觸發(fā)事件。Company組件中定義了觸發(fā)事件,點擊按鈕執(zhí)行sendMessage回調,該回調將觸發(fā)demo事件。
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
vue2.0 可折疊列表 v-for循環(huán)展示的實例
今天小編大家分享一篇vue2.0 可折疊列表 v-for循環(huán)展示的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09vue最強table vxe-table 虛擬滾動列表 前端導出問題分析
最近遇到個問題,后臺一次性返回2萬條列表數(shù)據(jù)并且需求要求所有數(shù)據(jù)必須全部展示,不能做假分頁,怎么操作呢,下面通過本文介紹下vue最強table vxe-table 虛擬滾動列表 前端導出問題,感興趣的朋友一起看看吧2023-10-10利用vuex-persistedstate將vuex本地存儲實現(xiàn)
這篇文章主要介紹了利用vuex-persistedstate將vuex本地存儲的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04利用Dectorator分模塊存儲Vuex狀態(tài)的實現(xiàn)
這篇文章主要介紹了利用Dectorator分模塊存儲Vuex狀態(tài)的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式
這篇文章主要介紹了vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10