VueJs class and style bindings

This entry is part 2 of 7 in the series VueJs

This episode in the VueJs series will focus on class and style bindings. It shall be a short lesson but all these little bits and pieces early on will help in the long term of coming together to be able to create much more complex things. Well lets move into bindings.

In VueJs you often need to manipulate stylings and classes on html elements and rather than having to deal with string manipulation and working out if something is there (jQuery), VueJs takes the approach of calculating a string based on an expression. In addition to Strings, the expressions can also evaluate to Objects or Arrays.

A quick tip from VueJs on this

Although you can use mustache interpolations such as class="{{ className }}" to bind the class, it is not recommended to mix that style with v-bind:class. Use one or the other!

On that tip I think it is best to always go with v-bind:

<div class="static" v-bind:class="{ 'class-a': isA, 'class-b': isB }"></div>
data: {
  isA: true,
  isB: false
}

output will then render as:

<div class="static class-a"></div>

This is a nice syntax to output what you need in terms of classes on your html elements, and guessing from the expressions resolving to truthy values then you can apply this much further to output these classes. We will explore this much further in future lessons.

Well the example above is nice, lets quickly show you the same but applied to styles and with array syntax.

quick note before, v-bind:class="" syntax can be shortened to just :class=""

So applying that to styles:

<div class="static" :style="[styleObjectA, styleObjectB]"></div>
data: {
  styleObjectA: {
    color: 'red',
    fontSize: '13px'
  },

  styleObjectB: {
    background: 'blue',
    border: '1px solid brown'
  }
}

output will then render as:

<div class="static" style="color:red; font-size:13px; background:blue; border: 1px solid brown;"></div>

Again simple and easy. Moving forward we will learn more and more around vue and build up to more complex stuff.

Thanks for reading!

Series Navigation<< VueJs an introductionVueJs directives introduction >>



Random Posts