关于Vue中组件之间传值

组件之间的通信的问题,组件之间的通信可以分为以下几种:

  1. 父子组件传递,父向子传递采用 props,子向父采用事件 emit。
  2. 非父子组件的传递,全局 event bus, 创建一个新的 vue 的实例,采用事件的方式通信,再者采用 vuex 全局状态管理。

父子组件相互通信方法详情

  1. 子组件通过 $emit 调用父组件的 method
// 父组件中定义 @updateInfo 调用的方法
<template>
  <user-popup @updateInfo="updateInfo"></user-popup>
</template>

methods: {
  updateInfo() {
    xxxxxx
  },
},

// 子组件在某个方法中进行调用,例如
saveInfomation() {
  this.$emit('updateInfo');
},
  1. 父组件通过 prop 向子组件进行传值
// 父组件内定义传递给子组件的值 userInformation
<template>
  <child :userInformation="userInfo"></child>
</template>

data() {
  return {
    userInfo: {
      type: Object,
      required: true,
    },
  };
},

// 子组件内通过 prop 获取父组件传递的值 userInformation
<template>
  <label>姓名:</label><span>{{userInformation.username}}</span>
</template>

props: {
  userInformation: {
    type: Object,
    required: true,
  }
}
  1. 父组件通过 $refs 调用子组件的 method
<template>
  <child ref="son"></child>
</template>

method: {
  parentMethod() {
    this.$refs.son.childMethod();
  },
},
  1. 直接用 this.$parent.xxx 调用父组件的方法

parent (Vue instance):指定已创建的实例之父实例,在两者之间创立父子关系。子实例可以用 this.$parent 访问父实例,子实例被推入父实例的 $children 数组中。

注意:this.$parentthis.$children 是访问组件的应急方法,更推荐使用 propevent实现父子组件通信。

非父子组件相互通信方法详情

  1. event bus

情景描述:brother.vue 和 sister.vue 两姊妹要通信,sister 要知道 brother 被点击了多少次,由于它们师兄和师妹的关系(平级),所以需要一个新的中间件 globalBus 来进行消息的传递。

globalBus.js

import Vue from 'vue';
export const globalBus = new Vue();

这里 import 了一个 vue 类,然后实例化并且将它 export, 实际上是创建了一个与 DOM 和程序的其他部分完全解耦的组件,它仅仅是一个组件所以非常的轻量。

brother.vue

<template>
  <button @click="clickCount"></button>
</template>

import { globalBus } from './globalBus';

export default {
  data() {
    return {
      counts: 0,
    };
  },
  method: {
    clickCount() {
      this.counts++;
      globalBus.$emit('countNumber', this.counts);
    },
  },
}

触发了 globalBus 的 countNumber 事件,返回参数 this.counts。

sister.vue

import { globalBus } from './globalBus';

export default {
  created() {
    this.total();
  },
  method: {
    total() {
      globalBus.$on('countNumber', (number) => {
        console.log(`brother 被点击了 ${number} 次。`);
      });
    },
  },
}

监听 globalBus 的 countNumber 方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章