Vue 组件通讯方式汇总

233 阅读3分钟

一、props 和 $emit (父子组件通讯)

父组件向子组件传递数据是通过 props 传递的,子组件传递数据给父组件是通过 $emit 触发自定义事件( v-on 是用来注册给子组件自定义事件的),props 以单向数据流的形式可以很好的完成父子组件的通信,单向数据流指的是就是数据只能通过 props 由父组件流向子组件,而子组件并不能通过修改 props 传过来的数据修改父组件的相应状态

Vue.component('child',{
    data(){
      return {
        mymessage:this.message
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @input="passData(mymessage)"> 
      </div>
    `,
    props:['message'], // 设置 props 属性值,得到父组件传递过来的数据
    methods:{
      passData(val){
        // 触发父组件中的事件,向父组件传值
        this.$emit('getChildData',val)
      }
    }
  })
  Vue.component('parent',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <child :message="message" v-on:getChildData="getChildData"></child>
      </div>
    `,
    data(){
      return {
        message:'hello'
      }
    },
    methods:{
      //执行子组件触发的事件
      getChildData(val){
        console.log(val)
      }
    }
  })

代码解析:父组件通过属性传递的方式将message数据给子组件,并且通过 v-on 绑定了一个getChildData事件来监听子组件的触发事件;子组件通过 props 得到相关的message数据,最后通过 this.$emit 触发了父组件的getChildData事件,完成了子组件向父组件的传值

二、$attrs$listeners (跨层级组件通讯)

比如父组件A下面有子组件B,组件B下面有组件C,这时组件A想传递数据给组件C,如果采用第一种方法,就必须让组件A通过prop传递消息给组件B,组件B在通过prop传递消息给组件C;要是组件A和组件C之间有更多的组件,那采用这种方式就很复杂了。Vue 2.4开始提供了 attrsattrs 和 listeners 来解决这个问题,能够让组件A之间传递消息给组件C

Vue.component('C',{
    template:`
      <div>
        <input v-model="$attrs.messagec" @input="passCData($attrs.messagec)"> 
      </div>
    `,
    methods:{
      passCData(val){
        //触发父组件A中的事件
        this.$emit('getCData',val)
      }
    }
  })
  Vue.component('B',{
    data(){
      return {
        mymessage:this.message
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @input="passData(mymessage)">
        <C v-bind="$attrs" v-on="$listeners"></C>
      </div>
    `,
    props:['message'],//得到父组件传递过来的数据
    methods:{
      passData(val){
        //触发父组件中的事件
        this.$emit('getChildData',val)
      }
    }
  })
  Vue.component('A',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <B :messagec="messagec" :message="message" v-on:getCData="getCData" v-on:getChildData="getChildData(message)"></B>
      </div>
    `,
    data(){
      return {
        message:'hello',
        messagec:'hello c' //传递给c组件的数据
      }
    },
    methods:{
      getChildData(val){
        console.log('这是来自B组件的数据')
      },
      //执行C子组件触发的事件
      getCData(val){
        console.log("这是来自C组件的数据:"+val)
      }
    }
  })

代码解析:C组件中之所以能直接触发getCData的原因在于B组件调用C组件时使用 v-on 绑定了$listeners 属性 ,在通过 v-bind 绑定 $attrs 属性,C组件可以直接获取到A组件中传递下来的 props(除了B组件中props声明的)

三、provide 和 inject (跨层级组件通讯)

父组件中通过 provider 来提供变量,然后在子孙组件中通过 inject 来注入变量。不论子组件有多深,只要调用了 inject 那么就可以获取到注入 provider 中的数据。而不是局限于只能从当前父组件的 prop 属性来获取数据,只要在父组件的生命周期内,子组件都可以调用。provide 和 inject 绑定并不是可响应的。但是如果传入的是一个可监听的对象,那么其对象的属性还是可响应的

Vue.component('child',{
    inject:['for'],//得到父组件传递过来的数据
    data(){
      return {
        mymessage:this.for
      }
    },
    template:`
      <div>
        <input type="tet" v-model="mymessage">
      </div>
  })
  Vue.component('parent',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <child></child>
      </div>
    `,
    provide:{
      for:'test'
    },
    data(){
      return {
        message:'hello'
      }
    }
  })

四、$parent$children (父子组件通讯)

在组件内部可以直接通过子组件 $parent 对父组件进行操作,父组件通过 $children 对子组件进行操作,要注意的是:这种方式是直接得到组件实例,使用后可以直接调用组件的方法或访问数据,弊端就是无法跨级或兄弟间通信

Vue.component('child',{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性
    },
    data(){
      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){
        this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @change="changeValue">
      </div>
  })
  Vue.component('parent',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <button @click="changeChildValue">test</button >
        <child></child>
      </div>
    `,
    methods:{
      changeChildValue(){
        this.$children[0].mymessage = 'hello';
      }
    },
    data(){
      return {
        message:'hello'
      }
    }
  })
  var app=new Vue({
    el:'#app',
    template:`
      <div>
        <parent></parent>
      </div>
    `
  })

五、$emit$on (跨层级组件通讯)

该方法又称中央事件总线,本质上就是新建一个Vue实例bus对象,然后通过bus.$emit触发事件,bus.$on监听触发的事件

Vue.component('brother1',{
    data(){
      return {
        mymessage:'hello brother1'
      }
    },
    template:`
      <div>
        <p>this is brother1 compoent!</p>
        <input type="text" v-model="mymessage" @input="passData(mymessage)">
      </div>
    `,
    methods:{
      passData(val){
        //触发全局事件globalEvent
        bus.$emit('globalEvent',val)
      }
    }
  })
  Vue.component('brother2',{
    template:`
      <div>
        <p>this is brother2 compoent!</p>
        <p>brother1传递过来的数据:{{brothermessage}}</p>
      </div>
    `,
    data(){
      return {
        mymessage:'hello brother2',
        brothermessage:''
      }
    },
    mounted(){
      //绑定全局事件globalEvent
      bus.$on('globalEvent',(val)=>{
        this.brothermessage=val;
      })
    }
  })
  //中央事件总线
  var bus=new Vue();
  var app=new Vue({
    el:'#app',
    template:`
      <div>
        <brother1></brother1>
        <brother2></brother2>
      </div>
    `
  })

六、父组件通过 ref 获取子组件

  • ref 有两个作用:

    1. 如果你把它作用到普通 HTML 标签上,则获取到的是 DOM
    2. 如果你把它作用到组件标签上,则获取到的是组件实例
  • 使用方式,在使用子组件的时候,给子组件添加 ref 属性,然后在父组件等渲染完毕后使用 $refs 访问子组件实例

  • $refs只会在组件渲染完成之后生效,并且它们不是响应式的。这仅作为一个用于直接操作子组件的“逃生舱”——你应该避免在模板或计算属性中访问 $refs

// 子组件
<template>
  <div>
    <h1>ref Child</h1>
    <input ref="input" type="text" v-model="value">
  </div>
</template>

<script>
export default {
  data () {
    return {
      value: ''
    }
  },
  methods: {
    focus () {
      this.$refs.input.focus()
    }
  }
}
</script>

<style>
</style>

// 父组件
<template>
  <div>
    <h1>ref Parent</h1>

    <child ref="c"></child>
  </div>
</template>

<script>
import child from './04-Child'
export default {
  components: {
    child
  },
  mounted () {
    this.$refs.c.focus()
    this.$refs.c.value = 'hello input'
  }
}
</script>

<style>

</style>