Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to Vue component via $refs

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')
            }
        })
    })
}
like image 970
Beatrix Avatar asked Dec 31 '22 18:12

Beatrix


2 Answers

You can use this:


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

like image 106
SherlockMac Avatar answered Jan 08 '23 01:01

SherlockMac


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>
like image 28
Abdelillah Aissani Avatar answered Jan 08 '23 02:01

Abdelillah Aissani