Several ways to use v-bind binding with Class and Style in Vue

Several ways to use v-bind binding with Class and Style in Vue

Adding/removing classes to elements is a very common behavior in project development. For example, website navigation will add an active class to the selected item to distinguish between selected and unselected styles. In addition to navigation, this method is also used in many other places to handle selection and unselection.

In addition to setting classes, we often set inline styles of elements in our projects. In the jQuery era, most of us used addClass and removeClass in combination to handle the addition/deletion of classes, and used the css() method to set/get the inline style of elements.

So how do we handle this kind of effect in Vue? In Vue, we can use the v-bind directive to bind our class and style. Next, let's see what methods Vue provides for binding them.

Object syntax binding Class

Switching tab pages is one of our most common effects. How to highlight the selected title? The common way is to dynamically switch the class.

<div id="app">
    <div class="button-group">
      <button
        v-for="(tab, index) in tabs" 
        v-bind:key="index" 
        v-bind:class="{active: currentTab === tab}" 
        v-on:click="currentTab = tab"
      >{{tab}}</button>
    </div>
    <component v-bind:is="currentTabComponent"></component>
</div>
<script>
Vue.component("tab1", {
    "template": "<p>This is tab 1</p>"
});
Vue.component("tab2", {
  "template": "<p>This is tab 2</p>"
});
Vue.component("tab3", {
  "template": "<p>This is tab 3</p>"
});
var vm = new Vue({
  el: "#app",
  data: {
    currentTab: "tab1",
    tabs: ["tab1", "tab2", "tab3"]
  },
  computed: {
    currentTabComponent() {
      return this.currentTab;
    }
  }
});
</script>

From the example we can see that whether the active class exists depends on whether the following expression is true or false. When it is true, the active class is added to the element, otherwise not.

Not only can we add one class, we can also add multiple classes at the same time, and they can coexist with the original classes.

<button 
    class="btn"
    v-bind:class="{'btn-primary': isPrimary, active: isActive}"
></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        isPrimary: true,
        isActive: true  
      }
    });
</script>

The rendering result is:

<button class="btn btn-primary active"></button>

We can also bind a data object directly

<button class="btn" v-bind:class="activePrimary"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        activePrimary: {
          'btn-primary': true, 
          active: true
        }
      }
    });
</script>

The rendering result is the same as above

<button class="btn btn-primary active"></button>

In addition, we can also use calculated properties to bind the class of the element

<button v-bind:class="activeClass"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        isActive: true
      },
      computed: {
        activeClass() {
          return {
            active: this.isActive
          }
        }
      }
    });
</script>

Array syntax binding class

Vue also supports adding classes to elements using arrays. Let’s modify the above example of adding classes to objects.

<button class="btn" v-bind:class="[primary, active]"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        primary: 'btn-primary',
        active: 'btn-active'  
      }
    });
</script>

In the above method, we bind a fixed one. What if we need to switch the class dynamically? We can use ternary expressions or use object syntax with arrays.

//Ternary expression <button v-bind:class="[isActive ? active : '', primary]"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        isActive: true,
        primary: 'btn-primary',
        active: 'btn-active'  
      }
    });
</script>
 
//Using object syntax in an array <button v-bind:class="[{active: isActive}, primary]"></button>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        isActive: true,
        primary: 'btn-primary'
      }
    });
</script>

Object syntax binding Style

The object syntax when binding inline styles looks very much like CSS, but it is actually a Javascript object. We can use camelCase or hyphen-separated names.

<div v-bind:style="{color: colorStyle, backgroundColor: background}">
Object syntax
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        colorStyle: 'red',
        background: 'blue'
      }
    });
</script>

Similar to classes, we can also use data objects to bind.

<div v-bind:style="style">Object syntax</div>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        style: {
          color: 'red',
          backgroundColor: 'blue'
        }
      }
    });
</script>

Array syntax binding Style

Vue allows us to bind multiple style objects to the same object at the same time.

<div v-bind:style="[style, fontStyle]">Object syntax</div>
<script>
    var vm = new Vue({
      el: "#app",
      data: {
        style: {
          color: 'red',
          backgroundColor: 'blue'
        },
        fontStyle: {
          fontSize: '18px'
        }
      }
    });
</script>

This concludes this article about several ways to use v-bind binding with Class and Style in Vue. For more information on Vue v-bind binding, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the similarities and differences between v-model and v-bind binding data in Vue
  • Understanding Vue dynamic attribute data binding (v-bind instruction) in one article
  • Use Vue's v-for and v-bind to switch list colors
  • Detailed explanation of custom instructions for v-bind:style effects in Vue
  • Vue v-bind dynamic binding class instance method
  • Vue directive form control binding v-model v-model combined with v-bind
  • Vue basics: v-bind attributes, class and style usage analysis
  • A brief analysis of the use and difference of v-bind v-model in Vue.js
  • Detailed explanation of Vue's common instructions v-if, v-for, v-show, v-else, v-bind, v-on
  • In Vue, v-bind uses the ternary operator to bind class instances
  • Tab method using v-bind:class in vue
  • Understanding v-bind in vue

<<:  Linux hardware configuration command example

>>:  MySQL 8.0.12 installation and configuration graphic tutorial

Recommend

Solution to the problem of adaptive height and width of css display table

Definition and Usage The display property specifi...

Sample code for implementing honeycomb/hexagonal atlas with CSS

I don’t know why, but UI likes to design honeycom...

The difference and execution method of select count() and select count(1)

Count(*) or Count(1) or Count([column]) are perha...

Vue3.0 routing automatic import method example

1. Prerequisites We use the require.context metho...

WeChat applet realizes multi-line text scrolling effect

This article example shares the specific code for...

Installation tutorial of mysql 5.7 under CentOS 7

1. Download and install the official MySQL Yum Re...

Detailed tutorial on installing Docker and docker-compose suite on Windows

Table of contents Introduction Download and insta...

js to realize web message board function

This article example shares the specific code of ...

XHTML introductory tutorial: Application of table tags

<br />Table is an awkward tag in XHTML, so y...

Introduction to using the MySQL mysqladmin client

Table of contents 1. Check the status of the serv...

Limit input type (multiple methods)

1. Only Chinese characters can be input and pasted...

Docker builds cluster MongoDB implementation steps

Preface Due to the needs of the company's bus...

How to use IDEA to configure tomcat and create JSP files

Before using idea to write JSP files, you need to...

MySQL learning notes help document

View system help help contents mysql> help con...