为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Vue.js

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

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

  1. Vuex



作者:vivi_0833
链接:https://www.jianshu.com/p/01c7e752684e


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消