javascript - 在父级中添加一个变量来触发一个函数 - Vue
问题描述
我试图在孩子的父母中调用一个函数。
我创建了一个组件,可以在我的 Vue 项目的多个页面上使用,一旦该函数运行,我想在父级上调用一个函数。
我可以通过这样做来实现这一点this.$parent.getLocations()
- 它有效。
然而,由于这是一个组件,我需要getLocations()
成为一个变量,这可能是getPets()
或getLunch()
例如。
我正在通过'Location'
组件,所以我可以使用它。
我试过:('${this.$parent}.get${this.type}s()}'
是this.type
)Location
和this.$parent + ".get" + this.type +" s()
但是,两者都不会触发该功能。
如何使 `getLocations 成为运行该函数的变量?
解决方案
It's an anti pattern. The child of the parent should not know about the parent's function.
In the child:
this.$emit('needs-locations', { type: this.type })
In the parent:
<child @needs-locations="getLocations" :locations="locations">
getLocations(type) {
api.then((locations) => this.locations = locations)
}
This will give you bidirectional communication without dependency.
推荐阅读
- html - 如何在第 1 列之前在移动视图中首先显示第 2 列
- excel - 难以使复制粘贴公式工作并压缩粘贴区域
- python - 我们可以限制任何机器学习算法中响应变量的值吗?
- html - 如何将我的 HTML 标签与 ASP.Net 单选按钮相关联?
- machine-learning - 将预先标记的检测图像添加到 ibm cloud.annotation.ai
- reactjs - 为什么不能给钩子的初始值一个空对象?
- android - 我想在我的设备上创建一个应用程序的链接,但它不工作
- nlog - 当我的布局以 ${pad...} 开头时,为什么 NLog 不产生任何输出
- dashboard - Grafana 中的散点图
- android - AndroidX:设置 setLifeCycleOwner 进行绑定时出错