组件间的通信:
1. 父组件 =》子组件:
(1).属性props
child: props:{ msg: String}
parent: <HelloWorld msg="Welcome to my summary"/>
(2).特性 $attrs
child: // 并未在props中申明 foo <p>{{$attrs.foo}}</p> 此时渲染结果为 <p>foo</p>
parent: <HelloWorld foo="foo" />
(3).引用refs
parent: <HelloWorld ref="hw"/> mounted() {this.$refs.hw.xx="xxxxx"}
child: <p>{{xx}}</p> data(){ return {xx: 'xxxxxxxx'} }
2. 子组件 =》 父组件: // 事件谁派发,谁监听
// child: this.$emit('add', good);
// parent: <Cart @add="cartAdd($event)" ></Cart>
3. 兄弟组件:通过共同父辈组件
通过共同的祖辈组件搭桥,$parent或$root
// brother1 this.$parent.$on('foo', handle)
// brother2 this.$parent.$emit('foo')
4. 祖先和后代之前
由于嵌套层数过多,传递props不切实际,vue提供了provide/inject API完成该任务
provide/inject: 能够实现祖先给后代传值
// ancestor provide() { return {foo: 'foo'} }
// descendant inject:['foo']
5. 任意两个组件之间: 事件总线或 vuex
事件总线: 创建一个Bus 类负责事件派发、监听和回调管理
// 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')
vuex: 创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更