Autoplay

    Update Attributes, Classes and Styles in Vue.js with v-bind

    Greg ThomanGreg Thoman

    Use v-bind:class and v-bind:style to compute html classes and inline styles from component data. Vue.js will automatically add vendor prefixes when using v-bind:style.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Here, we've got a list of inputs that are bound using V-model to our components data block. Let's create a dynamic class by using v-bind class, then create a ternary based on the result of size toggle. If true, return the string, "large," and if it's false, return an empty string.

    00:20 Let's add another class. We do that by turning v-bind class into an array. For the second inaudible in the array, let's create a key value pair. Vue will render this key if the value returns true. We can use v-bind disabled to bind the disable state of our button to a variable disabled.

    00:45 What if we wanted to bind to an entire block of inline styles? Let's add v-bind style and set that equal to styles. Styles will need to be a computed property in this case, so we'll create a computed block after data and add a styles method.

    01:00 That method will return a block of key value pairs. These keys and values will be displayed as inline styles in the Vue, so we need to use actual CSS properties. Now, we have a large rounded but disabled button with an orange background and white text that we can slide over to the left.

    Discuss

    Discuss