vue组件通信

208 阅读1分钟

同步数据方法 v-model和.sync

.sync

// 父组件:
<Son1 :value="mny" @input="change" />

// 子组件:
<button @click='change'>改变父组件的值</button>
methods(){
    change(){
        this.$emit('input', 200)
    }
}


// 父组件
<Son1 :value= 'mny' @update:value='(value) => this.mny=value'></Son1>
等价于
<Son1 :value.sync='mny' />

//子组件
<button @click='change'>改变父组件的值</button>
methods(){
    change(){
        this.$emit('update:value', 200)
    }
}

v-model

//父组件:
<Son1 v-model='mny' /> 
等价于
<Son1 :value='mny' @input='mny => this.mny=mny' />

// 子组件
<button @click='change'>改变父组件的值</button>
methods(){
    change(){
        this.$emit('input', 200)
    }
}

两者的区别

  • v-model有局限性,只能传value
  • aa.sync——update:aa,bb.sync——update:bb只要一一对应就可以 不一定是value

多层级传递数据

$parent

//父组件:
 <son :value='value' @input='change'/>
 
//子组件:
<grandson :value='value'/>

//子组件的子组件:
  <button @click="change">改变父组件的父组件的值</button>
  methods:{
    change(){
     // this.$parent.changeValue()
      this.$parent.$emit('input',1000)
    }
  }

向上通知

//main.js
  Vue.prototype.$dispatch = function(eventName,value){
  var parent = this.$parent
  while(parent){
    parent.$emit(eventName, value)
    parent = parent.$parent
  }
} 

// 子组件的子组件
<button @click="change">改变父组件的父组件的值</button>
methods:{
    change(){
      // this.$parent.changeValue()
      // this.$parent.$emit('update:value',1000)
      this.$dispatch('update:value',5)
    }
  }

向下通知

Vue.prototype.$broadcast = function(eventName,value){
    const broadcast = (children) =>{
        children.forEach(child => {
            child.$emit(eventName,value);
            if(child.$children){
                broadcast(child.$children)
            }
        })
    }
    broadcast(this.$children)
}

$attrs和$listenens

// 父组件 
$attrs 属性的集合
$listeners 方法的集合
v-bind 属性
v-on 方法
<Grandson v-bind='$attrs' v-on='$listeners'/>
可以获取父组件及他祖宗组件的数据和事件

注入数据

// 父组件
provide(){
    return {
        parent: this
    }
}

// 子组件
inject: [
    'parent'
]

ref

  • ref可以用到dom元素上,获取的是dom节点
  • 放到组件上获取的就是当前的组件

eventBus

// main.js
Vue.prototype.$bus = new Vue()

// 绑定
mounted(){
    this.$bus.$on('change',()=>{
        console.log(111)
    })
}

// 促发
mounted(){
    this.$nextTick(()=>{
        this.$bus.$emit('change')
    })
}