Vue.js $ children按组件名称

JavaScript

猪猪Harry

2020-03-12

我正在尝试通过名称访问特定的孩子。此刻,由于孩子的位置,我以此称呼孩子:

this.$root.$children[0]

只要那个孩子一直都是可以的,[0]但是如果有一种方法可以做到,那就太好了:

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

我一直认为这$refs可能是解决我的问题的方法,但永远找不到找到帮助我的方法。

有任何想法吗?

第1052篇《Vue.js $ children按组件名称》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
小哥Tony 2020.03.12

您不一定需要$refs,实际上,如果您具有深层嵌套的组件,则有时它们是不可行的。在搜索时,我已经多次找到该问答,但是由于我经常遇到这种情况,因此最终决定实施自己的解决方案。不要对老式循环感到厌恶,它们有两个原因是必要的,因为在我推动的每个迭代中,我都会测试x<descendants.length(而不是预先设置诸如len=descendants.length测试之类的东西)在第二个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;
}
神乐小宇宙Gil 2020.03.12

所有内容几乎相同,但是在Vue 2中,您需要使用:<details ref="detailsChild"></details>而不是v-ref。

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

路易猴子Pro 2020.03.12
this.$root.$children[0].constructor.name
Tom阳光 2020.03.12

您可以使用以下属性:

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

例如:

this.$root.$children.find(child => { return child.$options.name === "name"; });
理查德Near 2020.03.12

您所说的这个孩子真的是您要从中访问组件的孩子吗?在这种情况下,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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android