首页 > 解决方案 > 在父级中添加一个变量来触发一个函数 - Vue

问题描述

我试图在孩子的父母中调用一个函数。

我创建了一个组件,可以在我的 Vue 项目的多个页面上使用,一旦该函数运行,我想在父级上调用一个函数。

我可以通过这样做来实现这一点this.$parent.getLocations()- 它有效。

然而,由于这是一个组件,我需要getLocations()成为一个变量,这可能是getPets()getLunch()例如。

我正在通过'Location'组件,所以我可以使用它。

我试过:('${this.$parent}.get${this.type}s()}'this.typeLocationthis.$parent + ".get" + this.type +" s()

但是,两者都不会触发该功能。

如何使 `getLocations 成为运行该函数的变量?

标签: javascriptvue.jsvuejs2vue-component

解决方案


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.


推荐阅读