Vue.js | Dynamically Displaying Text or Lists
Let us set up Vue.js and use Vue to dynamically display data such as text and arrays.
First, Make Vue.js Available
- Vue 2.5.4
If you want to practice, using a CDN is the easiest way. It is introduced first in the official site’s Getting Started.
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
This URL always loads the latest version in development mode and displays detailed errors. In production, use the minified file.
In addition to a local environment, the official guide also introduces using https://jsfiddle.net. It is recommended when trying examples. On this site, each sample also has a code runner, so you can run examples immediately.
Vue.js does not necessarily require a build environment such as Webpack, so it is easy to get started.
Creating a Vue Instance
First, create a root instance using the Vue constructor function.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue Test</title>
</head>
<body>
<div id="app">Hello {{ message }}</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Vue.js!'
}
})
</script>
</body>
</html>
If a warning says that the element does not exist, write the JavaScript near the bottom of the body tag so it runs after the DOM has loaded. If you store it in a variable, you can access it from the console or externally as follows.
vm.message = "test"
Constructor options can specify data used by Vue.js, methods, mounted elements, and so on.
- el Selects the mount element.
- data Data handled by Vue.js.
- methods Methods used by the application.
When Should You Use new Vue?
Which tag should this Vue constructor function be used on? It may be unclear when using it for the first time.
The basic approach is to create one Vue root instance for one application, for example the entire blog if it is a blog, and then increase component parts.
Because Vue has a component feature for creating parts, you generally do not call new Vue separately for each part such as menus and forms. In that case, using components is almost essential, so it is best to learn them early.
Use Data as Properties
Define and use any data you want to manipulate in the data option.
new Vue({
el: '#app',
data: {
message: 'Vue.js!' // Use this data.
}
})
Data registered in data is automatically converted into reactive data when the instance is created. Once it becomes reactive data, you can synchronize data drawing through data binding and also perform processing in response to data changes.
When Vue loads a template, it first converts it into an ordinary JavaScript function called a render function. The render function builds a virtual DOM based on the registered data state, and the virtual DOM state is asynchronously reflected in the actual DOM.
Displaying Simple Text
Data properties and methods defined in Vue can be used or executed in the template with the same names.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vue Test</title>
</head>
<body>
<div id="app">
<p>Hello {{ message }}</p>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'Vue.js!'
}
})
</script>
</body>
</html>
To render data as text, write a template by placing the data name inside double curly braces like {{ message }}. This is a technique called Mustache and binds data as part of text content. The spaces on both sides are only for readability and can be omitted.
The example above has data named message at the root, so the text Vue.js! is rendered.
When using data in a method, specify this, as in this.message.
new Vue({
el: '#app',
data: {
message: 'Vue.js!'
},
created: function() {
alert(this.message)
}
})
created is one of the lifecycle methods.
Displaying Data as HTML
When displaying data with data binding, HTML is shown as escaped text to prevent XSS attacks. To display trusted data as HTML, write it as follows.
<span v-html="message"></span>
What Is XSS?
Rendering arbitrary dynamic HTML on a website is very dangerous because XSS vulnerabilities can easily occur. Display HTML only for trusted content. Be careful when displaying input values provided from outside.
Using Data in Element Attributes
For attributes, writing the following as you would for text does not display the value.
<p><a href="{{ url }}">{{ message }}</a></p> <!-- The URL is not displayed here. -->
To use data in an attribute, bind it with the v-bind directive.
<p><a v-bind:href="url">{{ message }}</a></p>
v-bind can also be abbreviated as :. This is shorter when there are many bindings.
<p><a :href="url">{{ message }}</a></p>
At first, if you are not used to it, it may be hard to read, so it may be better to write v-bind and abbreviate it later after you become familiar with it.
Excluding Some Parts from Vue Rendering
There may be cases where a certain element and its children do not need to be rendered by Vue. If you use the v-pre directive, it is recognized as normal HTML, so specifying it for content that does not include dynamic content can improve performance. The v-once directive renders only the first time and then treats it as static content. Even if message changes later, the element is not updated.
Shows Mustache text because it is not expanded:
<p><a v-bind:href="url" v-pre>Hello {{ message }}</a></p>
Releases reactivity after displaying message once:
<p><a v-bind:href="url" v-once>Hello {{ message }}</a></p>
These seem useful for improving performance when you have static HTML text or content that no longer needs to be monitored after display.
Reflecting Changes in Real Time
This comes a little early, but let us create a form that reflects changes in real time, a common sample in frameworks like this. Of course, this can also be done with jQuery or plain JavaScript, but managing it is very troublesome. Use the v-model directive to connect input forms and data.
<div id="app">
<input v-model="message">
<p>{{ message }}</p>
</div>
Create data named message in the data option.
new Vue({
el: '#app',
data: {
message: 'Hello.'
}
})
You may want to know what happens with checkboxes or select menus, but we will explain those in detail after covering more basics.
Directives Starting with v-
We have already seen v-bind and v-html, and many more Vue.js-specific attributes starting with v- will appear later. These are attributes with special roles in Vue.js and are called directives. The important point is that attribute values starting with v- are JavaScript expressions, not text. Vue.js has other special attributes as well, but if they do not start with v-, their values are basically simple strings, except for slot-scope. For directives without values, such as v-pre, you do not need to think too much about them.
Displaying Lists with Loops
If you create a slightly more elaborate application, you will naturally use more than simple text. Let us define and display various types of data.
Displaying a List
Display simple array data named list as follows.
new Vue({
el: '#app',
data: {
list: ['Apple', 'Banana', 'Strawberry']
}
})
To display a list, use the v-for directive.
<div id="app4">
<ul>
<li v-for="val in list">{{ val }}</li>
</ul>
</div>
The value of the v-for directive looks like JavaScript’s for..in statement, but its actual behavior is closer to for..of.
Displaying an Object
Let us display the following object data with a loop.
new Vue({
el: '#app',
data: {
list: {
a: 'Hamburger',
b: 'Bulgogi',
c: 'Pasta'
}
}
})
With parentheses, for objects you can optionally receive the value, key, and index; for arrays, you can receive the value and index.
<div id="app">
<ul>
<li v-for="(val, key) in list">(Key:{{ key }}) {{ val }}</li>
</ul>
</div>
The processing order of objects is not guaranteed because of JSON characteristics.
Displaying a List of Objects
Next, let us display a nested and slightly more complex list of objects with a loop.
new Vue({
el: '#app',
data: {
list: [
{ name: 'Tomato', price: 100 },
{ name: 'Lettuce', price: 200 },
{ name: 'Cucumber', price: 300 }
]
}
})
Because this is the same as looping over an array, you do not need to get the index unless it is necessary.
[Run code](/code/?id=29)
It is recommended to specify a unique key such as an ID with v-bind:key. If this list will be updated, adding a key is useful for rendering optimization and later manipulation. In the future, specifying keys may become required.
Now we have learned how to display various kinds of data. In the next chapter, we will update displayed data using Vue.