使用 Vue.js 怎么调用其他组件的方法

vm.$emit(event, [...args]) 触发当前实例上的事件,附加参数都会传给监听器回调。

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

  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 方法

另外的,我在项目中看到了另一种写法 globalBus.$emit('user-manage:updateInfo'); 我的理解是触发 user-usermage 文件的 updateInfo 方法。

 

 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值