我有两个组件 A 和 B,它们既不是彼此的子组件,也不是彼此的父组件。 A 的数据为
export default {
data() {
return {
info1: 'info1'
}
}
}
现在我想从组件 B 更新这个 info1 proppoerty。 可能吗?
最佳答案
您可以为此使用 $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。这是实现它的一种方法。
关于vue.js - 如何从 vuejs 中的另一个组件更新组件的数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445221/