How to add class to Vue component via $refs

23,505

Solution 1

You can use this:


this.$refs[field].$el.classList.value = this.$refs[field].$el.classList.value + 'my-class'

Solution 2

the only thing that you need to make sure of is that your config.requiredFields must include the ref name as a string and nothing more or less ... you can achieve that with :

   //for each ref you have 
    for (let ref in this.$refs) {
        config.requiredFields.push(ref)
     }
   // so config.requiredFields will look like this : ['one','two]

here is an example of a working sample :

Vue.config.devtools = false;
Vue.config.productionTip = false;

Vue.component('one', {
  template: '<p>component number one</p>'
})
Vue.component('two', {
  template: '<p>component number two</p>'
})

new Vue({
  el: "#app",
  beforeCreate() {
    let requiredFields = ['one','two'] //  config.requiredFields should be like this
    this.$nextTick(() => {
        requiredFields.forEach(field => {
            if(this.$refs[field]) {      
                this.$refs[field].$el.classList.add('my-class')
            }
        })
    })
}
})
.my-class {
  color : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <one ref="one" ></one>
  <two ref="two" ></two>
</div>

Solution 3

I know this question was posted ages ago, but I was playing around with something similar and came across a much easier way to add a class to $refs.

When we reference this.$refs['some-ref'].$el.classList it becomes a DOMTokenList which has a bunch of methods and properties you can access.

In this instance, to add a class it is as simple as

this.$refs['some-ref'].$el.classList.add('some-class')
Share:
23,505
Beatrix
Author by

Beatrix

Updated on November 06, 2021

Comments

  • Beatrix
    Beatrix over 2 years

    I need to add class name to some Vue components using their ref names. The ref names are defined in a config file. I would like to do it dynamically, to avoid adding class manually on each Vue component.

    I have tried to find each component using $refs and if found, add the class name to the element's class list. The class is added, but it is removed as soon as user interaction begins (e.g. the component is clicked, receives new value etc.)

    Here is some sample code I've tried:

    beforeCreate() {
        let requiredFields = config.requiredFields
        this.$nextTick(() => {
            requiredFields.forEach(field => {
                if(this.$refs[field]) {      
                    this.$refs[field].$el.classList.add('my-class')
                }
            })
        })
    }