This article describes several common ways to dynamically bind class by vue. Share it for your reference, as follows:
Object method
The simplest binding (the active here can be added without single quotes, and the following can be rendered the same)
:class="{ 'active': isActive }"
- Determine whether to bind an active
:class="{'active':isActive==-1}"
or
:class="{'active':isActive==index}"
- Bind and judge multiple
The first type (separated by commas)
:class="{ 'active': isActive, 'sort': isSort }"
The second type (put it in data)
//You can also write the object bound behind in a variable and put it in data, which can become the following:class="classObject" data() { return { classObject:{ active: true, sort:false } } }
The third type (using computed attribute)
:class="classObject" data() { return { isActive: true, isSort: false } }, computed: { classObject: function () { return { active: , sort: } } }
Array method
- Simple array
:class="[isActive,isSort]" data() { return{ isActive:'active', isSort:'sort' } }
- Combining array and ternary operators to determine the required class
(Note: The classes on both sides of the ":" after the ternary operator need to be given single quotes, otherwise they cannot be rendered correctly)
:class="[isActive?'active':'']"
or
:class="[isActive==1?'active':'']"
or
:class="[isActive==index?'active':'']"
or
:class="[isActive==index?'active':'otherActiveClass']"
- Combined with dynamic judgment of array objects
//The first active can be added without single quotes in the object, and the second sort must be added with single quotes in the object.:class="[{ active: isActive }, 'sort']"
or
:class="[{ active: isActive==1 }, 'sort']"
or
:class="[{ active: isActive==index }, 'sort']"
I hope this article will be helpful to everyone's programming.