How to Bind Styles and Classes in Vue.js
Dynamic Styling with Vue.js
Creating dynamic styles in Vue.js is super easy. By retrieving data from the Vue object you can set inline styles or even toggle a class depending on multiple states defined in your data.
Class Binding
First let's take a look at a basic class binding example. Let's say we have a button that we want to show only if 'showButton' is true. Like in our v-if post, we could simply add an inline attribute of v-if="showButton". But this time, let's toggle only the visibility via a class called "hide."
<button v-bind:class="{ hide: !showButton }"></button>
Here is our javascript:
var vm = new Vue({
data: { showButton: true }
})
Since 'showButton' is set to true, the hide class will appear as a class on the DOM element and would render like this.
<button>Click Me</button>
If you were to change your code to the following:
var vm = new Vue({
data: { showButton: false }
})
The following would render instead:
data: { showButton: false }
})
The following would render instead:
<button class="hide">Click Me</button>
Binding Styles
Binding styles is just as easy and works very similar.
Take this example. Say we want to show an input as red if the input is bad.
<input v-bind:style="{ color: inputColor }">
var vm = new Vue({
data: { inputColor: 'red' }
})
<input style="color: red">
Comments
Post a Comment