Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Vue.js 2.0 template syntax


May 07, 2021 Vue.js 2.0


Table of contents


Vue.js 2.0 template syntax

Vue .js HTML-based template syntax, allowing developers to declarely bind doMs to the data of the underlying Vue instance. All Vue.js templates are legitimate HTML, so they can be parsed by custom-followed browsers and HTML parsers.

On the underlying implementation, Vue compiles the template into a virtual DOM rendering function. Combined with the response system, Vue intelligently calculates the minimum cost of re-rendering components and applies them to DOM operations when the application state changes.

If you're familiar with virtual DOMs and prefer the raw power of JavaScript, you can also write render functions directly without templates, using the optional JSX syntax.

Interpolation

Text

The most common form of data binding is text interpolation using the "Mustache" syntax (double braces):

<span>Message: {{ msg }}</span>

The Mustache label will be replaced with the value of the msg property on the corresponding data object. Whenever the msg property on the bound data object changes, the contents at the interpolation are updated.

By using the v-once instruction, you can also perform a one-time interpolation, and when the data changes, the contents of the interpolation are not updated. But be careful that this affects all data bindings on the node:

<span v-once>This will never change: {{ msg }}</span>

Pure HTML

Double braces interpret the data as plain text, not HTML. In order to output real HTML, you need to use the v-html instruction:

<div v-html="rawHtml"></div>

Inserted content is treated as HTML -- data binding is ignored. N ote that you can't use v-html to composite local templates because Vue is not a string-based template engine. Components are better suited as basic units for UI reuse and composition.

Any HTML that is rendered dynamically on your site can be dangerous because it can easily lead to XSS attacks. Use HTML interpolation only for trusted content, never for user-provided content.

Property

Mustache cannot be used in HTML properties and should use the v-bind instruction:

<div v-bind:id="dynamicId"></div>

This is also valid for properties of Boolean values -- if the condition is valued false, the property is removed:

<button v-bind:disabled="someDynamicCondition">Button</button>

Use JavaScript expressions

So far, in our template, we've only bound simple property key values. In practice, however, for all data bindings, Vue .js provides full JavaScript expression support.

{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}
<div v-bind:id="'list-' + id"></div>

These expressions are resolved as JavaScript at the data scope of the Vue instance to which they belong. One limitation is that each binding can contain only a single expression, so the following example does not take effect.

<!-- 这是语句,不是表达式 -->
{{ var a = 1 }}
<!-- 流控制也不会生效,请使用三元表达式 -->
{{ if (ok) { return message } }}

Template expressions are placed in sandboxes and can only access a whitelist of global variables, such as Math and Date. You should not attempt to access user-defined global variables in a template expression.

Filter

Vue .js allows you to customize filters that are used as some common text formatting. The filter should be added at the end of the mustache interpolation, indicated by the "pipe character":

{{ message | capitalize }}

In Vue 2.x, filters can only be used in mustache bindings. In order to implement the same behavior in instruction bindings, you should use the calculate property .

The filter function always accepts the value of the expression as the first argument.

new Vue({
  // ...
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
})

Filters can be connected in series:

{{ message | filterA | filterB }}

Filters are JavaScript functions, so you can accept parameters:

{{ message | filterA('arg1', arg2) }}

Here, the string 'arg1' is passed to the filter as the second argument, and the value of the arg2 expression is evaluated and then passed to the filter as the third argument.

Instructions

Directives are special properties with v-prefixes. T he value of the instruction property is expected to be a single JavaScript expression (except v-for, discussed later). T he role of an instruction is to apply certain behaviors to the DOM accordingly when the value of its expression changes. Let's review the example in the introduction:

<p v-if="seen">Now you see me</p>

Here, the v-if instruction removes/inserts the element based on the true and false value of the expression seen.

Parameters

Some instructions can accept a "parameter" indicated by a colon after the instruction. For example, the v-bind instruction is used to update HTML properties in response:

<a v-bind:href="url"></a>

Here href is the argument that tells the v-bind instruction to bind the href property of the element to the value of the expression url.

Another example is the v-on instruction, which is used to listen for DOM events:

<a v-on:click="doSomething">

The parameter here is the event name of the listening. We will also discuss incident handling in more detail.

Modifier

Modifiers are half-horned periods. A special suffix that indicates that a specify should be bound in a special way. For example, the .prevent modifier tells the v-on instruction to call event.preventDefault() for the triggered event:

<form v-on:submit.prevent="onSubmit"></form>

Then when we take a closer look at v-on and v-model, we'll see more modifiers used.

Abbreviation

The v-prefix in the template is an obvious identification of a special Vue property. I t can be useful when you .js dynamic behavior for existing tags using Vue, but it can be a bit cumbersome for some frequently used instructions. A t the same time, v-.js become less important when building Vue and managing SPA for all templates. Therefore, the Vue .js provides special abbreviations for two of the most commonly used instructions:

v-bind abbreviation

<!-- 完整语法 -->
<a v-bind:href="url"></a>
<!-- 缩写 -->
<a :href="url"></a>

v-on abbreviation

<!-- 完整语法 -->
<a v-on:click="doSomething"></a>
<!-- 缩写 -->
<a @click="doSomething"></a>

They may look slightly different from normal HTML, but : and , are legitimate characters for property names and can be resolved correctly in all browsers that support Vue.js. A lso, they do not appear in the final rendered markup. Abbreviation syntax is completely optional, but as you learn more about what they do, you'll be glad to have them.