Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to element in method in Vue.js

Tags:

vue.js

How can I get reference to the element that fired the method in Vue.js? I have HTML like this:

 <input type="text" v-model="dataField" v-bind:class="dataFieldClass" /> 

And in my Vue.js viewmodel I have a method:

dataFieldClass: function () {     // Here I need the element and get its ID     // Pseudo code     var elementId = $element.id; } 

I know that it's possible to get the element from event (v-on:click), but this is not an event, it's a simple method returning CSS class for the element according to few conditions of the viewmodel. It should be computable as well, but the problem is the same.

like image 343
Ondrej Vencovsky Avatar asked Jun 15 '17 13:06

Ondrej Vencovsky


People also ask

How do I reference an element in Vue?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.

What is Vue REF ()?

ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

Can I use getElementById in Vue?

To use document. getElementById in Vue. js, we can assign a ref to the element we want to get. And then we can use this.


2 Answers

You can get the reference to your element in three ways

1. with Method Event Handlers (doc)

template:

<input type="text" v-model="dataField" v-bind:class="dataFieldClass" /> 

script:

dataFieldClass: function (e) {     const element = e.target; } 

2. with Inline Handlers (doc)

template:

 <input type="text" v-model="dataField" v-bind:class="dataFieldClass($event, otherArgument)" /> 

script:

dataFieldClass: function (e, otherArgument) {     const element = e.target; } 

3. with Refs (doc)

template:

 <input type="text" v-model="dataField" v-bind:class="dataFieldClass" ref="el"/> 

script:

dataFieldClass: function () {     const element = this.$refs.el; } 
like image 124
robinalaerts Avatar answered Sep 21 '22 15:09

robinalaerts


Maybe you could use ref?

<input type="text" v-model="dataField" v-bind:class="dataFieldClass" ref="el" /> 

And use it like this:

dataFieldClass: function () {     var elementId = this.$refs.el; } 

See documentation here: https://vuejs.org/v2/api/#ref

like image 31
Daniel Diekmeier Avatar answered Sep 19 '22 15:09

Daniel Diekmeier