vue组件通信大全

97 阅读1分钟

                                           

  • props
    父给子传值

    // child
    props: { msg: String }
    
    // parent
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    
  • ⾃定义事件

    ⼦给⽗传值
    // child
    this.$emit('add', good)
    
    // parent
    <Cart @add="cartAdd($event)"></Cart>
    
  • 事件总线

    任意两个组件之间传值常⽤事件总线 或 vuex的⽅式
    // main.js
    // 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))
        }
      }
    }
    Vue.prototype.$bus = new Bus()
    // 实践中通常⽤Vue代替Bus,因为Vue已经实现了相应接⼝
    Vue.prototype.$bus = new Vue()
    
    // child1
    this.$bus.$emit('foo')
    
    // child2
    this.$bus.$on('foo', handle)
    
  • vuex

    创建唯⼀的全局数据管理者store,通过它管理数据并通知组件状态变更
  • $parent/$root
    兄弟组件之间通信可通过共同祖辈搭桥,$parent或$root
    // brother1
    this.$parent.$on('foo', handle)
    
    // brother2
    this.$parent.$emit('foo')
    
  • $children

    ⽗组件可以通过$children访问⼦组件实现⽗⼦通信
    // parent
    this.$children[0].xx = 'xxx'
    
    // 注意:$children不能保证⼦元素顺序// 和$ref的区别为,ref可以
    // 和$refs的区别为,不管是原生节点还是自定义节点都可以使用$refs,$children只有自定义组件可以使用
    
  • $refs

    获取⼦节点引⽤
    // parent
    <HelloWorld ref="hw"/>mounted() {
     this.$refs.hw.xx = 'xxx'
    }
    
  • attrs/attrs/listeners

    包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当⼀个组件没有声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和 style 除外),并且可以通过 v-bind="$attrs" 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤
    // 孙子通知爷爷做事情
    // parent
    <Son @some-event="onSomeEvent">
    
    // son
    <Grandson v-on="$listeners">
    
    // grandson
    <button @click="$emit('some-event')">
    
    // parent
    <HelloWorld foo="foo"/>
    
    // child:并未在props中声明foo
    <p>{{$attrs.foo}}</p>
    
  • provide/inject
    能够实现祖先和后代之间传值
    provide() {
     return {foo: 'foo'} 
    }
    
    inject: ['foo']