组件通讯
props
父子间通讯
// child
props:{ msg:String }
// parent
<Child msg="this is parent" />
自定义事件
子传父
// child
this.@emit('add',this.count)
// parent
<Child @add="addCount(event)" />
事件总线
任意两个组件之间传值用$BUS 或者vuex
// 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.callback[name]){
this.callback[name].forEach(cb=>cb(args))
}
}
}
// main.js
Vue.prototype.$Bus = new Bus()
//child1
this.$Bus.$on('foo',handle)
// child2
this.$Bus.$emit('emit')
实践中通常用Vue代替Bus,因为Vue已经实现了相应接口
root
兄弟组件之间通讯,可以用共同的祖辈搭桥,root\
// brother1
this.$parent.$on('add',this.count)
// brother2
this.$parent.$emit('add')
$children
父组件可以通过$children访问子组件实现父子通讯
// parent
this.$children[0].xx='xxx'
注:$children不能保证子组件顺序
listeners
包含了父作用域中不被props所识别(且获取)的特定绑定(class和style除外),当一个组件没有声明任何props时,这里会包含所有父作用域的绑定(class和style除外),并且可以通过v-bind="$attrs"传入内部组件--在创建高级别组件时非常有用
// child 并未在props声明foo
<div>{{$attrs.foo}}</div>
// parent
<Child foo="foo" />
注意:目前该方法在uni-app中不适用
refs
获取子节点引用
// parent
<Child ref="xw" />
mounte4d(){
this.$refs.xw.xx="xxx"
}
provide/inject
能够实现祖先和后代之间传值
// ancestor
provide(){
return{
foo:"foo"
}
}
// descendant
inject:['foo']