Chapter 3. Styling with Vue

Vue helps you style your website or application in a few ways. v-bind:class and v-bind:style both have special helpers to help you set the class attribute and inline styles from your data, and when you’re using components with vue-loader, it’s possible to write scoped CSS that will affect only the component that CSS is writing in.

Class Binding

It’s common to use v-bind with the class attribute in order to add or remove classes depending on your data. Vue adds a couple of neat enhancements when using v-bind to set the class attribute, making it a lot nicer to work with.

Note

If you’ve used the classNames utility in React, you’ll be fairly familiar with the v-bind syntax. It’s basically the same, except wrapped in an array instead of being arguments of a function.

If you pass an array to v-bind:class, the classes in the array will be joined together. This is great for times when you want to set classes from your data or computed properties. Take the following example:

<div id="app">
  <div v-bind:class="[firstClass, secondClass]">
    ...
  </div>
</div>
<script>
  new Vue({
    el: '#app',
    data: {
      firstClass: 'foo'
    },
    computed: {
      secondClass() {
        return 'bar';
      }
    }
  });
</script>

In this example, firstClass equals foo and secondClass evaluates to bar, so the div element would be given a class attribute of foo bar.

In addition to using arrays, you can use objects. An object will conditionally add the keys as classes depending on the values: if the value is truthy, ...

Get Vue.js: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.