按组件名称的Vue.js $ children

问题描述 投票:17回答:6

我正试图通过名字访问一个特定的孩子。目前,由于孩子在哪里,我这样称呼孩子:

this.$root.$children[0]

只要那个孩子总是[0],这是好的,但如果有办法做某事,那就太好了:

this.$root.$children['detail']

我一直在想$refs可能是我的问题的答案,但永远找不到它有助于我的方式。

有任何想法吗?

javascript vue.js web-frameworks
6个回答
30
投票

您正在谈论的这个孩子真的是您要从中访问它的组件的孩子吗?在这种情况下,v-ref确实是答案:

// in the code of the parent component, access the referenced child component like this:

this.$refs.detailsChild
<!-- Template of the parent component, assuming your child Component is called Details -->
<details v-ref:details-child></details>

相关的API文档:http://vuejs.org/api/#v-ref


20
投票

您可以使用此属性:

this.$root.$children[0].$options.name

例如:

this.$root.$children.find(child => { return child.$options.name === "name"; });

3
投票

一切都差不多,但在Vue 2中你需要使用:<details ref="details-child"></details>而不是v-ref。

然后你需要做的就是使用this.$refs.details-child;,你可以访问它的任何属性。


1
投票
this.$root.$children[0].constructor.name

0
投票

你不一定需要$refs,事实上,如果你有深层嵌套的组件,它们有时是不可行的。我在搜索时已经多次发现这个Q&A,但最后我决定实施自己的解决方案,因为我经常遇到这种情况。不要为了旧学校的循环而犹豫不决,出于几个原因它们是必要的,其中一个原因是,我在每次迭代时测试x<descendants.length(而不是像前面那样设置len=descendants.length,并对其进行测试) m在第二个for循环中推进堆栈。

一,用法:

let unPersonalizable = matchingDescendants(this, /a.checkimprintfiinformation$/, {first: true});

执行:

function matchingDescendants(vm, matcher, options) {
    let descendants = vm.$children;
    let descendant;
    let returnFirst = (options || {}).first;
    let matches = [];

    for (let x=0; x<descendants.length; x++) {
        descendant = descendants[x];

        if (matcher.test(descendant.$vnode.tag)) {
            if (returnFirst) {
                return descendant;
            }
            else {
                matches.push(descendant);
            }
        }

        for (let y=0, len = descendant.$children.length; y<len; y++) {
            descendants.push(descendant.$children[y]);
        }    
    }

    return matches.length === 0 ? false : matches;
}

0
投票

昨晚我试图针对一些孩子。我试图在输入上调用el.focus()。我的问题是我试图通过按钮点击触发的实例方法来完成它,输入是在第三方库中我把它包装在另一个组件中。

我的解决方案是在我的包装组件上放一个ref

例如,如果您有这样的标记:

<my-dropdown ref="myDropdown"></my-dropdown>

my-dropdown内,你可以在其中一个孩子身上放另一个ref

<template>
    <div>
        <my-library-wrapper ref="libWrapper"></my-library-wrapper>
    </div>
</template>

my-library-wrapper内部,您可以从node_modules的库中导入,其中包含refs。大多数库都会对引物进行引用,以便您可以使用它们来定位它们。

现在,您可以使用以下代码开始定位我们的示例组件:

 console.log(this.$refs.myDropdown);

 console.log(this.$refs.myDropdown.$refs);

 console.log(this.$refs.myDropdown.$refs.libWrapper);

 this.$refs.myDropdown.$refs.libWrapper.$refs.someThing.focus();
 this.$refs.myDropdown.$refs.libWrapper.$refs.someThing.click();

乍一看,这可能看起来很奇怪,但与this.$refs.myDropdown.$children[0].$children[1].focus();这样的东西相比,这样做的好处是refs不那么脆弱。如果您或其他人稍后将<divs>添加到标记中,则使用refs的代码将不会中断,因为Vue按名称而不是相对距离查找这些引用的元素。

我的建议是把ref="something"放在某事上并做console.log(this.$refs.something.$refs);并看看你能看到什么,当你这样做时,做console.log(this.$refs.something);并看看那里有什么样的其他东西 - 像$attrs$children$el这样的东西。

© www.soinside.com 2019 - 2024. All rights reserved.