【问题标题】:How to update component's data property from another component in vuejs?如何从 vuejs 中的另一个组件更新组件的数据属性?
【发布时间】:2017-09-27 22:02:58
【问题描述】:

我有两个组件 A 和 B,两者都不是彼此的孩子或父母。 A 的数据为

export default {
    data() {
        return { 
           info1: 'info1'
        }
    }
}

现在我想从组件 B 更新这个 info1 属性。 有可能吗?

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

您可以为此使用 $root 和 $refs,将 ref 附加到两个组件,例如:

<component-a ref="compa"></component-a>
<component-b ref="compb"></component-b>

现在这里是重要的部分,您需要遵循每个组件的确切路径。示例您要在 B 中访问组件 A,使用

this.$root.$children[0].$refs.compa.info1

或者它会是

this.$root.$children[0].$children[0].$refs.compa.info1

this.$root.$children[0].$children[1].$refs.compa.info1

根据您的应用程序和组件之间的关系。通过这种方式,您可以从组件 A 访问和更新 info1。这是实现它的一种方法。

【讨论】:

    【解决方案2】:

    是的,这可能不止一种方式。我建议为此使用Vuex,因为当多个组件需要获取/更新值时,它会让事情变得更容易。

    Vuex 是一个用于状态管理的库,因此是为您想要实现的目标而构建的。它还使得在开发过程中检查值变得更加容易。

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 2017-11-18
      • 2021-04-05
      • 2019-02-05
      • 2017-06-12
      • 2018-03-07
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多