【问题标题】:Accessing nested child components in VueJS访问 VueJS 中的嵌套子组件
【发布时间】:2017-08-06 11:11:18
【问题描述】:

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

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

<Root>
    <Post>
        <AccountSelector>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
            <Account ref="anAccount"></Account>
        </AccountSelector>
    </Post>
</Root>

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

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

尽管存在 props 和 events,有时您可能仍需要在 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

ref和v-for一起使用时,得到的ref是一个数组 或包含镜像数据的子组件的对象 来源。

基本上在AccountSelector.vue里面你可以做this.$refs.anAccount.map(account =&gt; doThingToAccount(account))

编辑 上面的答案是为了访问一个直接的孩子。

目前无法使用$refs 访问非直接父/子组件。访问他们的数据的最佳方式是通过事件http://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication 或使用Vuex(我会推荐)。

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

【讨论】:

  • 谢谢!但是我怎样才能将这些数据冒泡到Post?我正在寻找访问 Post 内部的数据,比 AccountSelector 高一级。如果我这样做 post.$refs.anAccount 我会不确定。我错过了一个关卡。
  • 对不起,我现在得到你,我不确定你是否可以得到间接孩子。访问他们的数据的最佳方式是通过事件vuejs.org/v2/guide/… 或使用 Vuex(我会推荐)。没有这两种方法中的一种,非直接的亲子沟通非常棘手。
  • 感谢您的参考——那段确实说明我需要使用 Vuex。我实际上正在这样做,只是认为有更直接的方法!您可以修改您的答案,以便我接受它作为答案吗?
  • 我已经更新了答案以更直接地匹配所提出的问题
  • 我参加聚会的时间很晚,但活动巴士不是您最好的选择吗?
【解决方案2】:

您可以使用 $refs 访问嵌套组件数据,如果您想访问其中的 refs,您首先必须定位第一个 refs ([0]) 的第一个元素

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

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 2023-03-24
    • 2021-12-11
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2017-03-17
    相关资源
    最近更新 更多