Vue.js在组件中获取元素 [英] Vue.js getting an element within a component

查看:33
本文介绍了Vue.js在组件中获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,如何选择其元素之一?

I have a component, how can I select one of its elements?

我正在尝试获取该组件模板内的输入.

I'm trying to get an input that is within this component's template.

可能有多个组件,所以 querySelector 必须仅解析该组件的当前实例.

There could be multiple components so the querySelector must only parse the current instance of the component.

Vue.component('somecomponent', {
    template: '#somecomponent',
    props: [...],

   ...

    created: function() {
        somevariablehere.querySelector('input').focus();
    }
});

推荐答案

您可以使用 this.$ children 访问vuejs组件的子级.如果要在当前组件实例上使用查询选择器,则 this.$ el.querySelector(...)

you can access the children of a vuejs component with this.$children. if you want to use the query selector on the current component instance then this.$el.querySelector(...)

仅做一个简单的 console.log(this)即可向您显示vue组件实例的所有属性.

just doing a simple console.log(this) will show you all the properties of a vue component instance.

另外,如果您知道要在组件中访问的元素,则可以向其中添加 v-el:uniquename 指令,并通过 this.$ els.uniquename

additionally if you know the element you want to access in your component, you can add the v-el:uniquename directive to it and access it via this.$els.uniquename

这篇关于Vue.js在组件中获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆