JavaScript Expressions

vue.js logo

A little HTML, CSS, & JavaScript knowledge if recommended for this course.

To follow along, the starter folder is located in The Vue instance lesson.

Double curly braces (interpolation)

We have used the double curly braces so far, also referred to as interpolation, to output our data properties. And also in our loops to output the variable value.

Along with values generated by Vue.js, these double curly braces also support JavaScript expressions.

A JavaScript expression is JavaScript code which evaluates to a value.

Outputting expressions

At it's most simple, we could work with numbers and perform a calculation. Try these anywhere inside the index.html body section:

{{ 1 + 3 }}
{{ 10 / 2 }}
{{ Math.random() }}
{{ name.toUpperCase() }}
{{ name.length > 0 ? 'Welcome ' + name : 'Welcome guest' }}

Expressions in dynamic attributes

Also, we can add expressions into our dynamic attributes. Let’s say we wanted to only set our darkMode object if a condition is true:

<div :style="[10 < 5 ? darkMode : '', base]">

This condition is false (10 is not less than 5) so will remove the dark mode as we are setting an empty string. Switch this to 10 > 5 and darkMode will evaluate to true and set the style object.

There is also aother way of doing this. In our script.js, we still have the darkModeSet data property:

darkModeSet: false,

The following code will only set our darkMode object if darkModeSet is true:

<div :style="[darkModeSet ? darkMode : '', base]">

Toggle darkMode to be true/false and you will see the update in the browser.

Toggling this manually is not ideal, so next, we will introduce events so the color mode will react to clicking on a button.