IMG-LOGO

How to bind multiple css classes in Vue.js?

andy - 12 Jan, 2019 12040 Views 0 Comment

In this Vue.js tutorial, we are going to learn on how to bind multiple CSS classes into HTML HTML tag. So let's get started. I am going to use the Vue.js library script tag for a faster tutorial. So the first thing we have to do is to include the Vue.js library. I will use the development version of the library as this is just for a quick and demo development only.

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

We then need to create a html block element with an id on it so we can reference the id when we will initiate the Vue.js instance.

<div id="app">
	<div id="ourExampleDiv">
		This is our div example.
	</div>
</div>

We are going to create three css classes which will implement the font size, the color of a text and the font weight of a text.

<style>
	.red{
		color:#red;
	}
	
	.bold{
		font-weight:bold;
	}
	
	.size{
		font-size:2rem;
	}
</style>

Let's get started with our javascript code.

<script>
var app = new Vue({
	el: '#app',
	data: {
		textBold: 'bold'
	},
	methods: {
		applyRedColor(){
			return "red";
		}
	}
})
</script>

As you can see from above code, we are going to implement the multiple classes with the following conditions.

  1. We inject directly a css class textSize to the div tag.
  2. We inject a css class based on a method or function named ApplyRedColor.
  3. We inject a css class based on existing data variable.

We then need to modify our html code to use the Vue.js css class directive which is :class. This is the short keyword directive of v-bind:class.

<div id="app">
	<div id="ourExampleDiv" :class="['textSize', applyRedColor(), textBold]">
		This is our div example.
	</div>
</div>

When you view the source of the html using element inspector. You can see those 3 css classes have been added into the div tag.

Demo of Vue.js on binding multiple css classes.

Please see the following demo of a div tag with red big text.

This is our div example.

I hope this simple tutorial helps. If you have any question regarding with the code, feel free to post your comment below.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

Data binding in Vue.js

Understanding the basic concept of data binding in Vue.js. In this tutorial, you will learn your first v-model in Vue.js and how the data binding works.