Close read Vue official documentation series 🎉

introduce

The V-bind directive can bind style data to class and style attributes because they are not fundamentally different from normal HTMl-attributes. The V-bind directive is enhanced specifically for binding style data with v-bind:class and V-bind :style directives.

<btn class="green" :class="red"></btn> 
<! --<button class="green red"></button>-->
Copy the code

Vue merges the dynamic style data bound to :class and :style with the static string values of the native HTML class and style Attribute.

Binding HTML Class

Object syntax

<btn :class="classObj"></btn>
Copy the code
{
  computed: {
    classObj() {
      return {
        red: this.isRed,
        yellow: this.isYellow,
        green: this.isGreen, }; }},}Copy the code

When v-bind:class receives an object, the key of the object is the class name and the value is the status switch used to switch whether the class name is available.

Array syntax

<btn :class="['red', classObj, isBlue ? 'blue' : '']"></btn>
Copy the code
{
    data: {isBlue:true.classobj: {'green' : true,}}}Copy the code

V-bind: Class’s array syntax is more flexible, allowing for mixing strings with values of object types as well as simple ternary expression calculations.

Binding HTML Style

Object syntax

JavaScript objects with PascalCase names.

<btn :style="{fontSize:'20px'}"></btn>
Copy the code

To support Style CSS compatibility, the value in an object can be an array of values that can be selectively applied based on the current browser support.

<div :style="{display: ['-webkit-box', '-ms-flexbox', 'flex']}"></div>
Copy the code

Array syntax

V-bind :style array type, where each array element is a PascalCase named JavaScript object.

Array syntax allows multiple style objects to be applied to the same element.

<btn :style="[styleObj, styleObj2, {fontWeight:'bold'}]"></btn>
Copy the code
{
    data(){
        return {
            styleObj: {fontSize:'20px'}}},computed: {styleObj2(){
            return thisIsBlue? {color:'blue'} : null; }}}Copy the code

Used on components

The V-bind :class, native class, v-bind:style, and native style attributes used on a VUE component are inherited by the component’s root element and merged with the style and class of the component’s root element.