Javascript Vue.js $children 按组件名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35769139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:11:29  来源:igfitidea点击:

Vue.js $children by component name

javascriptvue.jsweb-frameworks

提问by Flakx

I'm trying to access a specific child by name. At the moment, because of where the child is, I'm calling the child by this:

我正在尝试按名称访问特定的孩子。目前,因为孩子在哪里,我这样称呼孩子:

this.$root.$children[0]

Which is ok as long as that child is always [0]but it would be great if there's a way to do something like:

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

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

I keep thinking $refsmight be the answer to my problem but can never find a way that it helps me.

我一直在想这$refs可能是我问题的答案,但永远找不到对我有帮助的方法。

Any ideas?

有任何想法吗?

回答by Linus Borg

Is this child you are talking about really a child of the component that you want to access it from? In this case, v-refis indeed the answer:

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

relevant API Documentation: http://vuejs.org/api/#v-ref

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

回答by drinor

You can use this property:

您可以使用此属性:

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

For example:

例如:

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

回答by Armin

All is pretty much the same, but in Vue 2 you need to use: <details ref="detailsChild"></details>instead of v-ref .

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

Then all you need to do is use this.$refs.detailsChild;and you can access any of it's properties.

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

回答by user4229130

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

回答by Dexygen

You don't necessarily need $refs, in fact sometimes they are not feasible if you have deeply nested components. I've found this Q&A several times while searching, but finally decidedly to implement my own solution since I run into this situation pretty frequently. Don't balk at the old-school for loops, they are necessary for a couple of reasons, for one, I test for x<descendants.length(rather than setting something such as len=descendants.lengthup front, and testing against that) on every iteration as I'm pushing on to the stack in the second for loop.

您不一定需要$refs,事实上,如果您有深层嵌套的组件,它们有时是不可行的。我在搜索过程中多次发现这个问答,但最终决定实施我自己的解决方案,因为我经常遇到这种情况。不要回避老式的 for 循环,出于几个原因,它们是必要的,首先,我在每次迭代时测试x<descendants.length(而不是预先设置一些东西len=descendants.length,然后针对它进行测试),因为我正在推动到第二个 for 循环中的堆栈。

First, usage:

一、用法:

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

Implementation:

执行:

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;
}

回答by agm1984

I was trying to target some children last night. I was trying to call el.focus()on an input. My problem was that I was trying to do it from an instance method that fired from a button click, and the input was in a 3rd party library AND I was wrapping that in another component.

昨晚我试图针对一些孩子。我试图调用el.focus()一个输入。我的问题是,我试图从一个从按钮单击触发的实例方法中执行此操作,并且输入位于 3rd 方库中,而我将其包装在另一个组件中。

The solution for me was to put a refon my wrapper component.

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

For example, if you have markup like this:

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

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

Inside my-dropdown, you could put another refon one of its children:

在里面my-dropdown,你可以把另一个ref放在它的一个孩子上:

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

Inside my-library-wrapper, you could import in a library from node_modulesthat has refs on it. Most libraries put refs on things so you can use those to target them.

在里面my-library-wrapper,你可以从node_modules一个有引用的库中导入。大多数库都将引用放在事物上,因此您可以使用它们来定位它们。

Now you could start to target our example components here with code like this:

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

 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();

At first glance, that might seem weird, but the benefit of doing this compared to stuff like this.$refs.myDropdown.$children[0].$children[1].focus();is that refsare much less brittle. If you or someone else adds <divs>into the markup later, the code using refswill not break because Vue is finding those ref-named elements by name, not by relative-distance.

乍一看,这似乎不可思议,但这样做的好处相比,一样的东西this.$refs.myDropdown.$children[0].$children[1].focus();refs易碎少得多。如果您或其他人<divs>稍后添加到标记中,则使用的代码refs不会中断,因为 Vue 是通过名称而不是相对距离来查找那些引用命名的元素。

My recommendation is to put ref="something"on something and do console.log(this.$refs.something.$refs);and take a look what you can see, and while you're doing that, do console.log(this.$refs.something);and see what kind of other things are available in there-- stuff like $attrsand $childrenand $el.

我的建议是穿上ref="something"一些东西,console.log(this.$refs.something.$refs);看看你能看到的东西,当你这样做的时候console.log(this.$refs.something);,看看那里还有哪些其他的东西——比如$attrsand$children$el