Vue總線Bus兄弟組件傳參

一、前言

? ?使用場景:在vue項目較小的情況,使用bus總線思路來完成vuex的傳值功能。

二、內(nèi)容

、、、

//util.js

export?default?class?Bus?{

??constructor()?{

????this.callbacks?=?{}

??}

??$on(name,?fn)?{

????this.callbacks[name]?=?this.callbacks[name]?||?[]

????this.callbacks[name].push(fn)

??}

??$emit(name,?args)?{

????if?(this.callbacks[name])?{

??????//?存在?遍歷所有callback

??????this.callbacks[name].forEach(cb?=>?cb(args))

????}

??}

}

//mai.js

import?Bus?from?'./utils/bus'

Vue.prototype.$bus?=?new?Bus()


//組件A

this.$bus.$on('log',?content?=>?{

??????console.log(content)

????})

//組件B

this.$bus.$emit('log',?120)

//父組件

<template>

??<div?class="home">

????<demo1?:msg1="msg111"?/>

????<demo2?:msg2="msg222"?/>

??</div>

</template>

、、、

總結(jié):

? ? Vue-Bus是一種總線思想,即各個兄弟組件通過Bus(即Vue實例)進行參數(shù)傳遞!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容