一、前言
? ?使用場景:在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ù)傳遞!