vue组件通信

296 阅读1分钟

父组件=>子组件

  • 属性props
// child
props: { msg: String }
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>
  • $attrs

一般与inheritAttrs: false v-bind="$attrs"一起使用

// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
  • refs
// parent
<HelloWorld ref="hw"/>
mounted() {
    this.$refs.hw.xx = 'xxx'
}
  • $children(子元素不保证顺序)
// parent
this.$children[0].xx = 'xxx'

子组件=>父组件

  • $emit
// child
this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>

兄弟组件

通过共同的祖辈组件搭桥,$parent$root

// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')

祖先和后代之间

由于嵌套层数过多,传递props不切实际,vue提供了 provide/inject API完成该任务

// ancestor
provide() {
    return {foo: 'foo'}
}
// descendant
inject: ['foo']

任意两个组件之间

事件总线 或 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.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')