vue.js - Vue.js 3 - 状态管理 - 如何从祖先调用方法
问题描述
我有一个 Vue 3 应用程序。我正在使用 Composition API,因为我读过它简化了状态管理。因此,我试图避免使用 VueX。也许,我遇到了一个值得考虑的情况。我目前在我的应用程序中有以下组件结构......
应用程序
+---------------------------------------------------+
| |
| +-----------------+ +--------------------+ |
| | Component 1 | | Component 2 | |
| | +-------------+ | | | |
| | | Component A | | +--------------------+ |
| | +-------------+ | |
| | | |
| | +-------------+ | |
| | | Component B | | |
| | +-------------+ | |
| +-----------------+ |
| |
+---------------------------------------------------+
整个应用程序围绕设置单个item
. item
最初可以通过或Component 1
在 中设置Component B
。item
您可以在via上设置属性Component A
。当用户单击 中的按钮时Component 2
,我想强制Component A
运行一个方法。但是,我还没有弄清楚如何做到这一点。
目前,Component 2
我this.$emit('forceRefresh')
在单击按钮时使用。但是,$emit
只有让我上堆栈。一旦我到达顶部,我不确定如何从堆栈中下去。但是,我尝试使用计算属性,Component A
但这不起作用。我觉得卡住了,好像我做错了。不过,我知道有办法,我只是不确定那是什么。
解决方案
您可以使用 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
})
推荐阅读
- android - 从 RecyclerView Room DB 中删除一行
- python - 试图获取 for 循环拾取的文件的索引
- android - 如何使用 Google Drive API 扫描 Android Studio 应用程序中的文档?
- excel - 打开没有路径的工作簿
- javascript - 带有样式组件的材质 ui 按钮
- java - Java中的匹配纸牌游戏
- java - 是否可以在 Vaadin 14 和 RouterLink 中添加 uri 的#fragment 部分?
- c++ - 需要帮助了解 Stockfish 中使用的 uci.h 文件
- ios - 邮递员 GET 请求的 Alamofire 等效项
- php - 为什么我的前端 Wordpress 登录表单卡在重定向循环中?