A small Vue.js app

Displaying text from a stored value

I have a Vue “app” that does nothing more than display some HTML elements according to its template (and some CSS rules).

Right now, the app’s template includes an <h2> element with the text “The app’s title” inside it. I typed “The app’s title” right into the template.

Goal

The task for this installment is to display some text from my Vue instance’s data object, rather than storing the text directly in the template.

This uses one-way data binding, where the app displays the current value of a property that may change. It is my first use of a Vue directive to make the app’s view reactive to the model.

Breakdown

  1. Add a data option to the Vue instance, with a key-value pair containing the text
  2. Bind the contents of the “app-title” element to the value of appTitle in data

1. Add a data option to the Vue instance, with a key-value pair containing the text

I’ll put an object called data into the Vue instance’s options object. This will be useful for storing all sorts of properties as the app grows. Inside data, a key-value pair (with key appTitle) will hold the text that the template will access and display.

var simpleAppWithText = new Vue({
  el: '.app02',
  data: {
    appTitle: 'This text comes from a key-value pair in the `data` option of the Vue instance'
  },
  template: // etc...

2. Bind the contents of the “app-title” element to the value of appTitle in data

I can now use “mustache” interpolation (double curly brackets) in the template to point Vue at the key appTitle within its data object, instead of typing text into the template:

<h2 id="app-title">{{appTitle}}</h2>

The contents of the app-title element are now bound to the value of appTitle – this is an example of one-way data binding, because there’s no way to do something with the display element that will change the value of appTitle inside data.

The demo isn’t spectacular; it looks pretty much the same as before, even though we know that under the hood, the title text comes from a different place in the Vue instance options:

Note that, because I am replacing the entire textContent of the element with the text of appTitle, I could use the v-text directive instead of the mustache syntax:

<h2 id="app-title" v-text="appTitle"></h2>

To individually control parts of the textContent of an element, v-text doesn’t do the job. Mustache interpolation does allow us to combine text interpolation with static text, or bindings to other properties, in the template; for example, I could write:

<h2 id="app-title"> The text of <code>appTitle</code> is: {{appTitle}}.</h2>

The result:

I haven’t looked into formatting of reactive text in Vue, but there is some capacity for this with filters.

Now that the app has somewhere to store properties (data), in the next step I will use it to store text input by the user.