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



作者:vivi_0833
链接:https://www.jianshu.com/p/01c7e752684e
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM