在 VueJS 中访问嵌套的子组件
Accessing nested child components in VueJS
使用 v2.2.2。我的 VueJS 应用程序中有以下结构。如何从我的 Post 组件上的方法访问所有帐户组件?帐户数量是动态的 - 我想获取所有加载的 Account
组件并迭代它们。
我知道这与$refs
和$children
有关,但我似乎无法找出正确的路径。
<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:
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>
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))
编辑
上面的答案是直接访问 child.
目前无法使用 $refs
访问非直接 parent / child 组件。访问他们数据的最佳方式是通过事件 http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication or by using Vuex(我会推荐)。
非直接 parent - child 如果没有这 2 种方法中的一种,通信将非常棘手。
您可以使用 $refs 访问嵌套组件数据,如果您想访问其中的引用,您首先必须定位第一个引用的第一个元素 ([0])
示例:parent.$refs[0].$refs.anAccount
使用 v2.2.2。我的 VueJS 应用程序中有以下结构。如何从我的 Post 组件上的方法访问所有帐户组件?帐户数量是动态的 - 我想获取所有加载的 Account
组件并迭代它们。
我知道这与$refs
和$children
有关,但我似乎无法找出正确的路径。
<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:
<div id="parent">
<user-profile ref="profile"></user-profile>
</div>
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))
编辑 上面的答案是直接访问 child.
目前无法使用 $refs
访问非直接 parent / child 组件。访问他们数据的最佳方式是通过事件 http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication or by using Vuex(我会推荐)。
非直接 parent - child 如果没有这 2 种方法中的一种,通信将非常棘手。
您可以使用 $refs 访问嵌套组件数据,如果您想访问其中的引用,您首先必须定位第一个引用的第一个元素 ([0])
示例:parent.$refs[0].$refs.anAccount