Vue.js getting an element within a component

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.

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

Solution 1:

vuejs 2

v-el:el:uniquename has been replaced by ref="uniqueName". The element is then accessed through this.$refs.uniqueName.

Solution 2:

There's a few options depending on what you're trying to access:

  • You can access the child components of a Vue.js component with this.$children

  • You can label specific DOM elements inside your template using ref="uniqueName" and refer to these later via this.$refs.uniqueName
    (but remember that you won't be able to refer to these until the component/app has finished mounting and performed an initial render)

  • If you're unable to label your elements, you can query the DOM for child elements using a CSS selector via this.$el.querySelector('.myClass > .childElement')
    (as above, the component/app needs to have finished mounting)

You can also explore by doing a simple console.log(this) inside your component and it will show you all the properties of your Vue component instance.