Learn
Styling Elements with Vue
Computed Style Objects

A common pattern for adding dynamic inline style objects is to add a dynamic Vue app property that generates the style object. For example, we could refactor the previous example as follows:

<h2 v-bind:style="breakingNewsStyles">Breaking News</h2>
const app = new Vue({ data: { breakingNewsStyles: { color: 'red', 'font-size': '32px' } } });

In this example, we store the style object, breakingNewsStyles, as a Vue app property and then make that object the value of v-bind:style. Using this pattern, we can make style objects for specific, reusable use cases.

This pattern also allows us to consolidate similar style-computing logic to a single computed property instead of computing styles on a rule-by-rule basis. Instead of creating a computed property for every rule that we want to apply to an element if it passes a certain condition, we can instead create a single computed property that checks the condition and then returns an object with all of the relevant style rules.

Instructions

1.

In the previous exercise, we created two separate computed properties that were checking for the same condition. This is unnecessarily repetitive code. Let’s refactor our code to a single computed property that will return complete style objects for each situation — if the form is valid and if it is not.

We’ve already removed the work from the previous exercise for you so you don’t have to go through the process of finding and deleting your code.

In app.js, let’s start by adding a computed property called submitButtonStyles with a value of the following function:

function() { if (this.formIsValid) { return { 'background-color': '#4c7ef3', cursor: 'pointer' } } else { return { 'background-color': 'gray', cursor: 'default' } } }

This function will check to see if the form is valid and will return the corresponding style objects from last exercise accordingly.

2.

Now let’s use our computed property to style our “Confirm Tickets” submit button.

In index.html, add a v-bind:style directive to the “Confirm Tickets” button that uses the object stored at submitButtonStyles to style the button.

After running your code, make sure that the submit works as expected — gray and no pointer at the start, and blue with a pointer once the required fields have been filled in and selected.

Folder Icon

Sign up to start coding

Already have an account?