Vue组件通讯
组件通信常用方式
-
-
event
-
-
边界情况
-
$parent
-
$children
-
$root
-
$refs
-
provide/inject
-
⾮prop特性
-
$attrs
-
$listeners
// Bus:事件派发、监听和回调管理
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]){
this.callbacks[name].forEach(cb => cb(args))
}
}
}
// main.js
Vue.prototype.$bus = new Bus()
// child1
this.$bus.$on('foo', handle)
// child2
this.$bus.$emit('foo')
实践中通常⽤Vue代替Bus,因为Vue已经实现了相应接⼝
import Vue from 'vue' const bus = new Vue() export default bus
import bus from '@/utils/bus
bus.$emit('message', 'hello');
import bus from '@/utils/bus' bus.$on('message', (e) => { console.log(e) })
// child:并未在props中声明foo <p>{{$attrs.foo}}</p> // parent <HelloWorld foo="foo"/>
// child <p v-on="$listeners">ssssssssssssssssssssddddddddd</p>
// parent <msgOne type="good" @click="onClick"></msgOne>

浙公网安备 33010602011771号