访问 VueJS 中的嵌套子组件 [英] Accessing nested child components in VueJS
问题描述
使用 v2.2.2.我的 VueJS 应用程序中有以下结构.如何从 Post 组件上的方法访问所有 Account 组件?帐户的数量是动态的 - 我想获取所有加载的 Account
组件并遍历它们.
我知道这与 $refs
和 $children
有关系,但我似乎无法找出正确的路径.
<发布><账户选择器><Account ref="anAccount"></Account><Account ref="anAccount"></Account><Account ref="anAccount"></Account></AccountSelector></发布></Root>
http://vuejs.org/v2/guide/components.html#Child-Component-Refs
<块引用>尽管存在 props 和 events,但有时您可能仍然需要直接访问 JavaScript 中的子组件.为此,您必须使用 ref 为子组件分配一个引用 ID.例如:
<user-profile ref="profile"></user-profile>var parent = new Vue({ el: '#parent' })//访问子组件实例var child = parent.$refs.profile
<块引用>
ref 和 v-for 一起使用时,得到的 ref 将是一个数组或包含镜像数据的子组件的对象来源.
基本上在 AccountSelector.vue
里面你可以做 this.$refs.anAccount.map(account => doThingToAccount(account))
编辑上面的答案是为了访问一个直接的孩子.
目前无法使用 $refs
访问非直接父/子组件.访问他们数据的最佳方式是通过事件 http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication 或使用 Vuex(我会推荐).
如果没有这 2 种方法中的一种,非直接的父子交流会非常棘手.
Using v2.2.2. I have the following structure in my VueJS app. How can I access all of the Account components from a method on my Post component? The number of Accounts is dynamic - I want to grab all of the loaded Account
components and iterate over them.
I know it's got something to do with $refs
and $children
, I just can't seem to figure out the right path.
<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.
Basically inside AccountSelector.vue
you can do this.$refs.anAccount.map(account => doThingToAccount(account))
Edit The above answer is for accessing a direct child.
Currently there is no way to access a non direct parent / child component with $refs
. The best way to get access to their data would be through events http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication or by using Vuex (Which i would recommend).
Non direct parent - child communication is very tricky without 1 of these 2 methods.
这篇关于访问 VueJS 中的嵌套子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!