Vue几种通信方式

102 阅读2分钟

使用方式和例子

1. props和$emit

// 父组件
Vue.component('parent', {
  template:`
    <div>
      <p>this is parent component!</p>
      <child :message="message" v-on:getChildData="getChildData"></child>
    </div>
  `,
  data() {
    return {
      message: 'hello'
    }
  },
  methods:{
    // 执行子组件触发的事件
    getChildData(val) {
      console.log(val);
    }
  }
});


// 子组件
Vue.component('child', {
  template:`
    <div>
      <input type="text" v-model="myMessage" @input="passData(myMessage)">
    </div>
  `,
  /**
   * 得到父组件传递过来的数据
   * 这里的定义最好是写成数据校验的形式,免得得到的数据是我们意料之外的
   *
   * props: {
   *   message: {
   *     type: String,
   *     default: ''
   *   }
   * }
   *
  */
  props:['message'], 
  data() {
    return {
      // 这里是必要的,因为你不能直接修改 props 的值
      myMessage: this.message
    }
  },
  methods:{
    passData(val) {
      // 数据状态变化时触发父组件中的事件
      this.$emit('getChildData', val);
    }
  }
})
  • 1)、 父组件传递了 message 数据给子组件,并且通过v-on绑定了一个 getChildData 事件来监听子组件的触发事件;

  • 2)、 子组件通过 props 得到相关的 message 数据,然后将数据缓存在 data 里面,最后当属性数据值发生变化时,通过 this.$emit 触发了父组件注册的 getChildData 事件处理数据逻辑。

2、$attrs 和 $listeners

// 组件A
Vue.component('A', {
  template: `
    <div>
      <p>this is parent component!</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: {
    // 执行B子组件触发的事件
    getChildData(val) {
      console.log(`这是来自B组件的数据:${val}`);
    },
    
    // 执行C子组件触发的事件
    getCData(val) {
      console.log(`这是来自C组件的数据:${val}`);
    }
  }
});

// 组件B
Vue.component('B', {
  template: `
    <div>
      <input type="text" v-model="mymessage" @input="passData(mymessage)"> 
      <!-- C组件中能直接触发 getCData 的原因在于:B组件调用 C组件时,使用 v-on 绑定了 $listeners 属性 -->
      <!-- 通过v-bind 绑定 $attrs 属性,C组件可以直接获取到 A组件中传递下来的 props(除了 B组件中 props声明的) -->
      <C v-bind="$attrs" v-on="$listeners"></C>
    </div>
  `,
  /**
   * 得到父组件传递过来的数据
   * 这里的定义最好是写成数据校验的形式,免得得到的数据是我们意料之外的
   *
   * props: {
   *   message: {
   *     type: String,
   *     default: ''
   *   }
   * }
   *
  */
  props: ['message'],
  data(){
    return {
      mymessage: this.message
    }
  },
  methods: {
    passData(val){
      //触发父组件中的事件
      this.$emit('getChildData', val)
    }
  }
});

// 组件C
Vue.component('C', {
  template: `
    <div>
      <input type="text" v-model="$attrs.messagec" @input="passCData($attrs.messagec)">
    </div>
  `,
  methods: {
    passCData(val) {
      // 触发父组件A中的事件
      this.$emit('getCData',val)
    }
  }
});
    

在上面的例子中,我们定义了 A,B,C 三个组件,其中组件B 是组件 A 的子组件,组件C 是组件B 的子组件。

  • 1). 在组件 A 里面为组件 B 和组件 C 分别定义了一个属性值(message,messagec)和监听事件(getChildData,getCData),并将这些通过 props 传递给了组件 A 的直接子组件 B;
  • 2). 在组件 B 中通过 props 只获取了与自身直接相关的属性(message),并将属性值缓存在了 data 中,以便后续的变化监听处理,然后当属性值变化时触发父组件 A 定义的数据逻辑处理事件(getChildData)。关于组件 B 的直接子组件 C,传递了属性 $attrs 和绑定了事件 $listeners
  • 3). 在组件 C 中直接在 v-model 上绑定了 $attrs 属性,通过 v-on 绑定了 $listeners

最后就将 $attrs 和 $listeners 单独拿出来说说吧!

  • $attrs:包含了父作用域中不被 prop 所识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定属性 (class和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件。
  • $listeners:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。

3、中央事件总线 EventBus

对于父子组件之间的通信,上面的两种方式是完全可以实现的,但是对于两个组件不是父子关系,那么又该如何实现通信呢?在项目规模不大的情况下,完全可以使用中央事件总线 EventBus 的方式。如果你的项目规模是大中型的,那你可以使用我们后面即将介绍的 Vuex 状态管理

EventBus 通过新建一个 Vue 事件 bus 对象,然后通过 bus.$emit 触发事件,bus.$on 监听触发的事件。

// 组件 A
Vue.component('A', {
  template: `
    <div>
      <p>this is A component!</p>
      <input type="text" v-model="mymessage" @input="passData(mymessage)"> 
    </div>
  `,
  data() {
    return {
      mymessage: 'hello brother1'
    }
  },
  methods: {
    passData(val) {
      //触发全局事件globalEvent
      this.$EventBus.$emit('globalEvent', val)
    }
  }
});

// 组件 B
Vue.component('B', {
  template:`
    <div>
      <p>this is B component!</p>
      <p>组件A 传递过来的数据:{{brothermessage}}</p>
    </div>
  `,
  data() {
    return {
      mymessage: 'hello brother2',
      brothermessage: ''
    }
  },
  mounted() {
    //绑定全局事件globalEvent
    this.$EventBus.$on('globalEvent', (val) => {
      this.brothermessage = val;
    });
  }
});

//定义中央事件总线
const EventBus = new Vue();

// 将中央事件总线赋值到 Vue.prototype 上,这样所有组件都能访问到了
Vue.prototype.$EventBus = EventBus;

在上面的实例中,我们定义了组件 A 和组件 B,但是组件 A 和组件 B 之间没有任何的关系。

  • 1)、 首先我们通过 new Vue() 实例化了一个 Vue 的实例,也就是我们这里称呼的中央事件总线 EventBus ,然后将其赋值给了 Vue.prototype.$EventBus,使得所有的业务逻辑组件都能够访问到;
  • 2)、 然后定义了组件 A,在组件 A 里面定义了一个处理的方法 passData,主要定义触发一个全局的 globalEvent 事件,并传递一个参数;
  • 3). 最后定义了组件 B,在组件 B 里面的 mounted 生命周期监听了组件 A 里面定义的全局 globalEvent 事件,并在回调函数里面执行了一些逻辑处理。

中央事件总线 EventBus 非常简单,就是任意组件和组件之间打交道,没有多余的业务逻辑,只需要在状态变化组件触发一个事件,然后在处理逻辑组件监听该事件就可以。该方法非常适合小型的项目!

4、provide 和 inject

// 定义 parent 组件
Vue.component('parent', {
  template: `
    <div>
      <p>this is parent component!</p>
      <child></child>
    </div>
  `,
  provide: {
    for:'test'
  },
  data() {
    return {
      message: 'hello'
    }
  }
});

// 定义 child 组件
Vue.component('child', {
  template: `
    <div>
      <input type="tet" v-model="mymessage"> 
    </div>
  `,
  inject: ['for'],	// 得到父组件传递过来的数据
  data(){
    return {
      mymessage: this.for
    }
  },
});

在上面的实例中,我们定义了组件 parent 和组件 child,组件 parent 和组件 child 是父子关系。

  • 1)、 在 parent 组件中,通过 provide 属性,以对象的形式向子孙组件暴露了一些属性
  • 2)、 在 child 组件中,通过 inject 属性注入了 parent 组件提供的数据,实际这些通过 inject 注入的属性是挂载到 Vue 实例上的,所以在组件内部可以通过 this 来访问。

5、$parent 和 $children

这里要说的这种方式就比较直观了,直接操作父子组件的实例。$parent 就是父组件的实例对象,而 $children 就是当前实例的直接子组件实例了,不过这个属性值是数组类型的,且并不保证顺序,也不是响应式的。

// 定义 parent 组件
Vue.component('parent', {
  template: `
    <div>
      <p>this is parent component!</p>
      <button @click="changeChildValue">test</button>
      <child />
    </div>
  `,
  data() {
    return {
      message: 'hello'
    }
  },
  methods: {
    changeChildValue(){
      this.$children[0].mymessage = 'hello';
    }
  },
});

// 定义 child 组件
Vue.component('child', {
  template:`
    <div>
      <input type="text" v-model="mymessage" @change="changeValue" /> 
    </div>
  `,
  data() {
    return {
      mymessage: this.$parent.message
    }
  },
  methods: {
    changeValue(){
      this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值
    }
  },
});

在上面实例代码中,分别定义了 parent 和 child 组件,这两个组件是直接的父子关系。两个组件分别在内部定义了自己的属性。在 parent 组件中,直接通过 this.$children[0].mymessage = 'hello'; 给 child 组件内的 mymessage 属性赋值,而在 child 子组件中,同样也是直接通过this.$parent.message 给 parent 组件中的 message 赋值,形成了父子组件通信。

关于 $parent 和 $children 这对属性的详细介绍可以查询官网文档!

适用场景

父子组件通信

父->子`props`,子->父 `$on$emit`

获取父子组件实例 `$parent$children`

`Ref` 获取实例的方式调用组件的属性或者方法

`Provideinject` 官方不推荐使用,但是写组件库时很常用

兄弟组件通信

`Event Bus` 实现跨组件通信 `Vue.prototype.$bus = new Vue`
`Vuex`

跨级组件通信

`Vuex`
`$attrs、$listeners`
`Provide、inject`