Summarize several ways of writing dynamic classes in vue

Object syntax (active here can be added or not in single quotes)

1The following syntax indicates that the existence of the active class will depend on the truthiness of the data isActive.

<div v-bind:class="{ active: isActive }"></div>
<div v-bind:class="{ active: isActive, sort: isSort }"></div>

2 The v-bind:class directive can also coexist with ordinary class attributes.

<div
  class="static"
  v-bind:class="{ active: isActive }"
></div>

3 The bound data object does not have to be defined inline in the template:

<div v-bind:class="classObject"></div>
data() {
	return {
		classObject: {
    		active: true,
   			static: false
 	 	}
	} 
}

4 You can also bind a computed property of the returned object here

<div v-bind:class="classObject"></div>
data: {
	return {
	    isActive: true,
  		error: null
	} 
},
computed: {
  classObject: function () {
    return {
      active: this.isActive,
      static: this.error
    }
  }
}

Array syntax

1 only array

<div :class="[isActive,isSort]"></div>

data() {
  return{
    isActive:'active',
    isSort:'sort'
 }
}

Rendered as

<div class="active sort"></div>

2 Array combined with ternary operator
Note:

  • The class on both sides of the ":" after the ternary operator needs to be enclosed in single quotes, otherwise it will not be rendered correctly.
  • The class name in the array needs to be quoted, otherwise it will not be rendered correctly.
// 当isActive 为true时class为activeClass, false时为errorClass,otherClass是一直存在
<div v-bind:class="[isActive ? 'activeClass': 'errorClass', 'otherClass']"></div>

3 Array objects combined with dynamic judgment
Note: When using object syntax in an array, the previous active does not need to be single quotes in the object, but the subsequent sort still needs to be added with single quotes.

:class="[{ active: isActive }, 'sort']"

Guess you like

Origin blog.csdn.net/wh13821662259/article/details/116238644