Vue 组件通信 知识点

697 阅读2分钟

前情提要

vue组件通信方式很多人不知道啥时候采用哪种方式来解决,这里做个笔记给需要的人

父子组件通信

父子组件通信最基本就是 propemit

prop 和 emit

  • 父传子
    • 子组件定义 prop ,父组件通过 传参赋值 的方式
      • 父组件
      <child :defineData='originData' />
      
      data(){
         return {
           originData: 123
         }
      }
      
      • 子组件
      prop: {
        defineData: {
            type: Number,
            default: 0
        }
      }
      
  • 子传父
    • emit 返回方法名和变量,父组件接收
      this.$emit('methodName', val);
    

父子组件双向绑定

如果父子组件数据需要双向绑定

  1. .sync 方式同步数据
    <child :defineData.sync='originData' />
  1. emitupdate:defineData 的方式
    this.$emit('update:defineData', newVal);

隔代组件通信

隔代组件通信通常使用 $parent$children

$parent$children

比如 爷组件 和 孙组件 的通信

// 孙子组件访问爷组件
this.$parent.$parent.methodName();

// 爷组件访问孙子组件
this.$children.$children.methodName();

provide 和 inject

如果不想疯狂写$parent$children ,也可以用 provideinject

在任意组件 provide 一个数据, 组件下的子组件可以用 inject 直接接收

// Parent.vue
export default {
    provide() {
        return {
            name: 'Stone'
        }
    }
}
// Child.vue
export default {
   inject: ['name'],
   mounted() {
       console.log(this.name)
   }
}

Vuex 通信

vuexstate 定义全局变量,用 commitdispatch 操控 mutationaction

eventBus 事件车

可以自定义 eventBus 事件车,在组件 mounted 渲染完毕的时候挂载事件车, 销毁时 销毁事件车。 这个方法现在一般用 vuex 代替,所以就不多详谈,放个代码。

/**
 * 此文件为事件车的分发中心
 * 提供两个方法,$get,$off
 */

import Vue from 'vue';
import { getObjectType } from '@util';

// 事件车存储,key为事件车的唯一标识,value为事件车
const BUSES = {};

/**
 * 获取事件车实例
 * @param {*} key 事件车的唯一标识符
 */
function getInstance(key) {
  let type = getObjectType(key);

  if (type !== 'string') {
    return new Error('Param Key Must Be String');
  }

  let instance = BUSES[key];
  if (!instance) {
    instance = new Vue();
    BUSES[key] = instance;
  }

  return instance;
}
/**
 * 销毁实例
 * @param {*} key 事件车的唯一标识符
 */
function destroyedInstance(key) {
  let type = getObjectType(key);

  if (type !== 'string') {
    return new Error('Param Key Must Be String');
  }

  let instance = BUSES[key];
  if (instance) {
    instance.$off();
    BUSES[key] = null;
  }

  return true;
}

export default {
  $get: getInstance,
  $off: destroyedInstance,
};