Vue.js: Class is bound to Style

         The class list and inline style of operation elements are a common requirement of data binding. Because they are all attribute s, we can use   v-bind   Deal with them: just calculate the string result through the expression. However, string splicing is cumbersome and error prone. Therefore, in   v-bind   be used for   class   and   style   Vue.js has been specially enhanced. In addition to strings, the type of expression results can also be objects or arrays.

1, Bind HTML Class

Object syntax

         We can pass it on to  : class   (v-bind:class   An object to dynamically switch classes:

<div :class="{ active: isActive }"></div>

         The syntax above indicates   active   Whether this class exists or not will depend on the data property   isActive   of   truthiness . You can dynamically switch multiple classes by passing in more fields in the object. In addition,: Class   Instructions can also be used with ordinary   class   Attributes coexist. When there are the following templates:

<div
  class="static"
  :class="{ active: isActive, 'text-danger': hasError }"
></div>

          And the following data:

data() {
  return {
    isActive: true,
    hasError: false
  }
}

         The rendered result is:

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

         When   isActive   perhaps   hasError   When changes are made, the class list is updated accordingly. For example, if   hasError   The value of is   true, the class list will become   "static active text-danger".

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

<div :class="classObject"></div>
data() {
  return {
    classObject: {
      active: true,
      'text-danger': false
    }
  }
}

         The rendering result is the same as above. We can also bind a return object here Calculation properties . This is a common and powerful pattern:

<div id="webapp">
<!--    Bind calculated properties-->
    <div :class="classObject"></div>
</div>

<script>
    // Create Vue and return application instance
    const webappVM = Vue.createApp({
        data() {
            return {
                isActive: true,
                error: null
            }
        },
        computed: { // Calculation properties
            classObject() {
                return { // When isActive is true and there is no error message, class = 'active'
                    active: this.isActive && !this.error,
                    // If there is an error message and the error message type is fatal class = 'text danger'
                    'text-danger': this.error && this.error.type === 'fatal'
                }
            }
        }
    }).mount('#webapp')
</script>

Array syntax

         We can pass an array to  : class to apply a list of classes:

<div :class="[activeClass, errorClass]"></div>
data() {
  return {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
}

         The rendered result is:  

<div class="active text-danger"></div>

         If you want to switch class es in the list according to conditions, you can use a ternary expression:

<div :class="[isActive ? activeClass : '', errorClass]"></div>

         This will always add   errorClass, but only in   isActive   For truth [1]   Add only when   activeClass. However, it is cumbersome to write this when there are multiple conditional class es. Therefore, object syntax can also be used in array syntax:

<div :class="[{ active: isActive }, errorClass]"></div>

Use on components

         When you use on a custom component with a single root element   class   attribute, these classes will be added to the element. Existing classes on this element will not be overwritten. For example, if you declare this component:

<div id="app">
    <!--    Use custom components and add two new ones class-->
    <my-component class="baz boo"></my-component>
</div>

<script>
    const app = Vue.createApp({})
    // Custom components
    app.component('my-component', {
        // Two class es are defined in the template
        template: `<p class="foo bar">Hi!</p>`
    })

    app.mount("#app");
</script>

         The HTML will be rendered as:

<p class="foo bar baz boo">Hi</p>

         The same applies to class es with data binding:

<my-component :class="{ active: isActive }"></my-component>

         When isActive is true [1]   When, HTML is rendered as:

<p class="foo bar active">Hi</p>

         If your component has multiple root elements, you need to define which parts will receive this class. have access to  $ attrs   Component properties to do this:

<div id="app">
<!--    Use custom components and add new ones class-->
    <my-component class="baz"></my-component>
</div>

<script>
    const app = Vue.createApp({})

    app.component('my-component', {
        // The p tag will accept the new class
        template: `
    <p :class="$attrs.class">Hi!</p>
    <span>This is a child component</span>
  `
    })

    app.mount("#app");
</script>

        html render result:

         You can Non prop Attribute   Section to learn more about component property inheritance.

2, Bind inline style

Object syntax

   : style   The object syntax is very intuitive - it looks very much like CSS, but it's actually a JavaScript object. CSS property names can be named with camel case or kebab case (remember to enclose them in quotation marks):

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data() {
  return {
    activeColor: 'red',
    fontSize: 30
  }
}

         It is usually better to bind directly to a style object, which makes the template clearer:

<div :style="styleObject"></div>
data() {
  return {
    styleObject: {
      color: 'red',
      fontSize: '13px'
    }
  }
}

         Similarly, object syntax is often used in conjunction with the calculated properties of the returned object.

Array syntax

  : style   The array syntax of can apply multiple style objects to the same element:

<div :style="[baseStyles, overridingStyles]"></div>

Auto prefix

         stay  : style   One is required for use in   vendor prefix   (browser engine prefix), Vue will automatically detect and add the corresponding prefix. Vue uses runtime detection to determine which styles of properties are supported by the current browser. If the browser does not support a property, Vue tests several times to find a prefix that supports it.

Multiple value

         You can provide an array containing multiple values for the property in the style binding. It is often used to provide multiple prefixed values, such as:

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

         This will render only the last value in the array that is supported by the browser. In this case, if the browser supports flexbox without browser prefix, only rendering will be performed   display: flex.

Tags: Javascript Vue.js css

Posted on Wed, 06 Oct 2021 17:03:53 -0400 by nishith82