Vue.js makes developing front end apps easy. However, there are still chances that we’ll run into problems.
In this article, we’ll look at some common issues and see how to solve them.
There are various ways to change the class name on an element dynamically.
We can use the :class
or v-bind:class
binding.
For instance, we can write:
<div v-bind:class="getClass()"></div>
Then in getClass
, we can return an object with the class names as the property keys and the condition to display them as the values:
methods:{
getClass(){
return {
'checked': this.content.shouldCheck,
'unchecked': !this.content.shouldCheck
}
}
}
We apply the checked
class to the div if this.content.shouldCheck
is true
. Otherwise, we apply the unchecked
class if this.content.shouldCheck
is false
.
We can also pass in any arguments we want:
methods:{
getClass(prop){
return {
'checked': this.content[prop],
'unchecked': !this.content[prop]
}
}
}
Then we can write:
<div v-bind:class="getClass(prop)"></div>
in our template to return the class names by the property name of this.content
. Also, we can write any expression that returns a string with the class name we want to apply.
For instance, we can write:
<div v-bind:class="checked"></div>
where checked
is a computed property:
computed: {
checked() {
return this.content.checked ? 'checked' : 'unchecked';
}
}
checked
is a computed property that returns the string with the class name we want depending on the this.content.checked
value.
#javascript #programming #software-development #web-development #vue #vue.js