关于vue.js:在VueJS中访问嵌套的子组件

Accessing nested child components in VueJS

使用v2.2.2。 我的VueJS应用程序具有以下结构。 如何从"发布"组件上的方法访问所有"帐户"组件? 帐户的数量是动态的-我想获取所有已加载的Account组件并对其进行迭代。

我知道这与$refs$children有关,我似乎无法找出正确的路径。

1
2
3
4
5
6
7
8
9
<Root>
    <Post>
        <AccountSelector>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
        </AccountSelector>
    </Post>
</Root>

http://vuejs.org/v2/guide/components.html#Child-Component-Refs

Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using ref. For example:

1
2
3
4
5
6
  <user-profile ref="profile"></user-profile>


var parent = new Vue({ el: '#parent' })
// access child component instance
var child = parent.$refs.profile

When ref is used together with v-for, the ref you get will be an array
or an object containing the child components mirroring the data
source.

基本上在AccountSelector.vue内部,您可以执行this.$refs.anAccount.map(account => doThingToAccount(account))

编辑
上面的答案用于访问直接子级。

当前无法使用$refs访问非直接的父/子组件。 获取其数据的最佳方法是通过事件http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication或使用Vuex(我建议这样做)。

如果没有这两种方法中的一种,非直接的父-子沟通非常棘手。


您可以使用$ refs访问嵌套的组件数据,如果要访问其中的ref,则首先必须将第一个ref([0])的第一个元素作为目标。

例如:parent.$refs[0].$refs.anAccount