Luk*_*een 27 vue.js vue-component vuejs2
使用v2.2.2.我的VueJS应用程序中有以下结构.如何从Post组件上的方法访问所有Account组件?帐户的数量是动态的 - 我想抓住所有已加载的Account组件并迭代它们.
我知道它有什么做$refs和$children我刚才似乎无法找出正确的道路.
<Root>
<Post>
<AccountSelector>
<Account ref="anAccount"></Account>
<Account ref="anAccount"></Account>
<Account ref="anAccount"></Account>
</AccountSelector>
</Post>
</Root>
Run Code Online (Sandbox Code Playgroud)
Dan*_*ble 34
http://vuejs.org/v2/guide/components.html#Child-Component-Refs
尽管存在道具和事件,但有时您可能仍需要直接访问JavaScript中的子组件.要实现此目的,您必须使用ref为子组件分配引用ID.例如:
<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
Run Code Online (Sandbox Code Playgroud)
当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(我推荐).
没有这两种方法中的一种,非直接的亲子沟通非常棘手.
小智 6
您可以使用 $refs 访问嵌套组件数据,如果您想访问其中的 refs,您首先必须定位第一个 refs ([0]) 的第一个元素
例子: parent.$refs[0].$refs.anAccount