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:
<divid="app"><divv-bind:class="[firstClass, secondClass]">...</div></div><script>newVue({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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access