Home  >  Article  >  Web Front-end  >  vue.js binds class and style styles

vue.js binds class and style styles

高洛峰
高洛峰Original
2017-01-12 13:29:271064browse

A common requirement for data binding is to manipulate the element's class list and its inline styles. Since they are all attributes, we can use v-bind to handle them: we just need to evaluate the final string of the expression. However, string concatenation is cumbersome and error-prone. Therefore, Vue.js specifically enhances v-bind when used with classes and styles. In addition to strings, the result type of an expression can also be an object or an array.

Use v-bind:class or :class to bind style or class

Bind class

<div class="test">
  <div :class="{active:isActive,cc:isCc}"></div>
 </div>

js code

var myVue = new Vue({
   el: ".test",
   data: {
     isActive:true,
     isCc:false
   },
 });

Or the following code can also be implemented

<div class="test">
   <div :class=classObject></div>
 </div>

js code

var myVue = new Vue({
    el: ".test",
    data: {
      classObject:{
        active:true
      }
    },
  });

pass the class through the array Binding

<div class="test">
  <div :class="[activeClass,error]">dsdsd</div>
</div>

js code

var myVue = new Vue({
   el: ".test",
   data: {
     activeClass:"active",
     error:"ddd"
   },
 });

Bind style attribute

<div class="test">
    <div :style=styleObject>dsdsd</div>
  </div>

js code

var myVue = new Vue({
  el: ".test",
  data: {
    styleObject:{
     color: "red",
      fontSize: "30px"
    }
  },
});

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to vue.js binding classes and styles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn