首页 > 解决方案 > Vue.js 3 - 状态管理 - 如何从祖先调用方法

问题描述

我有一个 Vue 3 应用程序。我正在使用 Composition API,因为我读过它简化了状态管理。因此,我试图避免使用 VueX。也许,我遇到了一个值得考虑的情况。我目前在我的应用程序中有以下组件结构......

应用程序

+---------------------------------------------------+
|                                                   |
| +-----------------+    +--------------------+     |
| | Component 1     |    | Component 2        |     |
| | +-------------+ |    |                    |     |
| | | Component A | |    +--------------------+     |
| | +-------------+ |                               |
| |                 |                               |
| | +-------------+ |                               |
| | | Component B | |                               |
| | +-------------+ |                               |
| +-----------------+                               |
|                                                   |
+---------------------------------------------------+

整个应用程序围绕设置单个item. item最初可以通过或Component 1在 中设置Component Bitem您可以在via上设置属性Component A。当用户单击 中的按钮时Component 2,我想强制Component A运行一个方法。但是,我还没有弄清楚如何做到这一点。

目前,Component 2this.$emit('forceRefresh')在单击按钮时使用。但是,$emit只有让我上堆栈。一旦我到达顶部,我不确定如何从堆栈中下去。但是,我尝试使用计算属性,Component A但这不起作用。我觉得卡住了,好像我做错了。不过,我知道有办法,我只是不确定那是什么。

标签: vue.js

解决方案


您可以使用 Vue.js 事件总线。本质上,事件总线是一个 Vue.js 实例,它可以在一个组件中发出事件,然后直接在另一个组件中侦听并响应发出的事件——无需父组件的帮助。

这是可以帮助您的参考链接。 1 https://blog.logrocket.com/using-event-bus-in-vue-js-to-pass-data-between-components/

export const bus = new Vue(); //in main.js

import { bus } from '../main'; //in component "B" and in click call the method and insted of emitting do
bus.$emit('changeIt', 'forceRefresh');

in component "A" in Mounted() add also import{ bus } 
bus.$on('changeIt', (data) => {
  //do the component refresh
})

推荐阅读