In this article, you will learn about dynamic style and class bindings in Vue.js. With the v-bind:style directive, you will visualize your font size on a click event. With v-bind:class, you will observe how to apply multiple classes to elements.
While this is possible with DOM manipulation, Vue.js allows you to dynamically render both styling and classes with concise lines of code and takes advantage of its data model structure. Let’s develop a way in Vue.js to increase or decrease font size based on user input.
To this end, Vue provides us with the v-bind:style directive. Within your App.js file, instantiate a Vue instance and include your data model:.
Create two buttons in your index.html file, and a paragrapth that takes in the v-bind:style directive:.
On each click event, the v-bind:style directive increments and decrements the value of your fontSize variable.
This attaches the value of fontSize to the CSS font-size property. If needed, add multiple style objects to the v-bind:style directive.
- In your App.js file, include the style objects as follows:.
- In your index.html file, provide an array of the style objects:.
- Note: Take caution the order of your style objects in the array, as logic in following elements overrides previous ones.
Now that you’ve reviewed style bindings let’s consider dynamic classes in Vue.js. Applying styles directly can get complex as the requirements change. To help with this, the v-bind:class directive provides a way to bind classes to content in an element. For example, you may need to underline the element’s text and change the color and font-weight. While this is possible to implement with a style binding, Vue.js allows you to include additional performance with the v-bind:class directive.
To achieve this, create an array of menuItems and a selected variable with a default value of 'Home' in your App.js file:. In your index.html file, apply a v-for loop within an ordered list to iterate through the elements in the menuItems array.
With each click event, the v-bind:class directive assigns the value of the selected variable to the current element in menuItems. This permits you to pass several classes into your ordered list element, and adds any styling listed in CSS:.
You can also pass multiple classes in an array using the v-bind:class directive. Define an array of classes in your data model within the App.js file:. In your index.html file, refer to your classArray using the v-bind:class directive.
This will apply both the selected and the underlined classes to the element.