Get reference to element in method in Vue.js Get reference to element in method in Vue.js vue.js vue.js

Get reference to element in method in Vue.js


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


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


What about using the ref pattern. Put ref="someName" in your DOM element, and access it in your method with this.$refs["someName"] (you can pass 'someName' as parameter to your method).

Note that's not a very good pattern except if for some reason you really need the DOM element. Otherwise just pass a relevant parameter to your method.

It's not a good method mainly because it has a major drawback: there is no $refs the first time the vue is rendered (because the element is not present yet). So you should force the vue to render twice.

If you have multiple elements inside a v-for loop, then this.$refs["someName"] becomes an array. You can get it to work with some adaptation, here is an example:

new Vue({  el: '#app',  data() {    return {      fields: [{          name: 'field1',          value: 'value1'        },        {          name: 'field2',          value: 'value2'        }      ]    };  },  methods: {    dataFieldClass(index) {      if (!this.$refs.fields) {        // First render, the element is not there yet        return '';      } else {        // Here is the element        console.log(this.$refs.fields[index]);      }    }  },  mounted() {    // Force the instance to render a second time    this.$forceUpdate();  }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script><div id="app">  <label v-for="(field, index) in fields">    {{ field.name }}:    <input ref="fields" :value="field.value" v-bind:class="dataFieldClass(index)">  </label></div>