父给子传值
// child
props: { msg: String }
// parent
<Child msg="hello child"/>
子给父传值
// child
this.$emit('toPar', msg)
// parent
<Child @toPar="getSon($event)"></Child>
兄弟组件之间通信可通过共同祖辈搭桥,$parent或$root。
// brother1
this.$parent.$emit('foo', data)
// brother2
this.$parent.$on('foo', data=>console.log(data))
⽗组件可以通过$children访问⼦组件实现⽗⼦通信。
this.$children获取当前组件的所有子组件对象。通过下标访问对应的具体组件。
注意:$children属性是不保证子组件的顺序的,因为$children是根据你页面加载组件的顺序去确定子组件在 $children数组中的顺序。页面销毁,子组件顺序会重新排序。不安全。
// parent
this.$children[0].xx = 'xxx'
父组件访问命名子组件数据
// parent
<Child ref="son"/>
this.$refs.son.xx = 'xxx'
包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当⼀个组件没有声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和 style 除外),并且可以通过 vbind="$attrs" 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤。
// parent
<Child foo="foo"/>
// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
//爷爷定义孙子用
// 爷爷给孙子隔代传值
<Child msg="foo" @some-method="onSomeEvent"></Child>
onSomeEvent(e){
//e为孙子的传值
}
// 儿子只做展开,起一个载体的作用
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// 孙子使⽤
<div @click="$emit('some-method','data传值给爷爷')">
{{msg}}
</div>
任意两个组件之间传值
// Bus:事件派发、监听和回调管理
class Bus {
constructor(){
this.callbacks = {}
}
//发布
$emit(name, args){
if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args))
}
}
//接收
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
}
// main.js
Vue.prototype.$bus = new Bus()
项目中通常⽤Vue代替Bus,因为Vue已经实现了$on和$emit
// main.js
Vue.prototype.$bus = new Vue()
// child1
this.$bus.$emit('foo',data)
// child2
this.$bus.$on('foo', data=>console.log(data))
任意两个组件之间传值
创建唯⼀的全局数据管理者store,通过它管理数据并通知组件状态变更
vuex详细使用
跨组件传值,数据的流只能是向下传递,即祖先和后代之间传值
// 祖先,注入依赖
provide() {
return {foo: 'foo'}
}
// 后代使用
inject: ['foo']