父组件=>子组件
props
//child
props: ["message"],
//parent
<HelloWorld message="hello world"></HelloWorld>
特性$attrs
//child里没有在props里声明foo,可以用如下方式取
this.$attrs.foo
//parent
<HelloWorld foo="foo"></HelloWorld>
问题1:props和$attrs的区别
props需要声明才能取到值,子类需要主动接收属性
$attrs不需要声明可以取到值,子类不用主动接收属性,会直接放在子类根元素上。在props里声明的属性不会在$attrs里取到
引用refs
//parent 想修改子组件里的xx值
<HelloWorld foo="foo" ref='fx'></HelloWorld>
this.$refs.fx.xx='xxxx'
子元素$children
// parent
this.$children[0].xx = 'xxx'
问题2:$refs和$children 的区别
$refs元素或者组件标签上添加ref属性指定一个引用信息,引用信息将注册在父组件的$refs对象上,使用$ref来指向dom元素或者组件实例,
需要注意:
$refs不能在created生命周期中使用 因为在组件创建时候 该ref还没有绑定元素
如果想在method中使用,使用 this.$nextTick(() => {}) 等页面渲染好再调用,这样就可以了
$children 访问子组件实例,返回的是一个子组件数组 因为是异步,所以不保证顺序的,
子组件=>父组件
//child
this.$emit('addTest',message)
//parent
<Cart v-on:addTest="cartAdd"></Cart>
兄弟组件:通过共同父辈组件
通过共同的祖辈组件搭桥,$parent或$root。
// brother1
this.$parent.$on('foo', handle)
// brother2this.$parent.$emit('foo')
祖先和后代之间
由于嵌套层数过多,传递props不切实际,vue提供了 provide/inject API完成该任务
provide/inject:能够实现祖先给后代传值
// ancestor
provide() { return {foo: 'foo'}
}
// descendant
inject: ['foo']
任意两个组件之间:
事件总线 或 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')