The use of the template

When developing with Vue, the template can be written in one of the following three ways:

  • Vue full version, templates can be written directly in HTML:

    <div id="app">
      <p>{{ n }}</p>
      <button @click="add">+ 1</button>
    </div>
    <script>
    new Vue({
      el: '#app'.data: { 
        n: 0 
      },
      methods: { 
        add () {
          this.n += 1}}})</script>
    Copy the code
  • Vue full version, templates can be written in the template option:

    <div id="app"></div>
    <script>
    new Vue({
      template: `
        <div>
          <p>{{ n }}</p>
          <button @click="add">+ 1</button>
        </div>', data: {n: 0}, methods: {add () {this.n += 1}}}).$mount('#app') // div#app will be replaced by the template</script>
    Copy the code
  • The Vue runtime version, which puts the template inside the

    <template> <div> <p>{{ n }}</p> <button @click="add">+1</button> </div> </template> <script> export default { // data Data () {return {n: 0}}, methods: {add () {this.n += 1}}} </script>Copy the code

The above three writing methods all use Vue’s unique template syntax, which is described in the Vue document as follows:

Vue uses AN HTML-based template syntax that allows developers to declaratively bind the DOM to the data of the underlying Vue instance. All vue. js templates are valid HTML, so they can be parsed by compliant browsers and HTML parsers.

On the underlying implementation, Vue compiles the template into a virtual DOM rendering function. Combined with a responsive system, Vue is able to intelligently calculate the minimum number of components that need to be rerendered and minimize DOM operations.

You can also write the render function without templates, using the optional JSX syntax.

What template syntax does Vue have?

The interpolation

Text interpolation

To display properties in data on a page, we can interpolate the text using the double brace syntax:

<template> <div>{{name}}</div> </template> <script> export default {data () {return {name: 'Luffi'}}</ script>Copy the code

The content in the braces is replaced with the value of the name property on the data object. Also, whenever the name property changes on the data object, the content in the braces is updated.

HTML insert

The double-brace syntax only interprets the data as plain text, not HTML code. To print real HTML, use the V-HTML directive:

<template> <div> <p v-html="rawHtml"></p> </div> </template> <script> export default { data () { return { rawHtml: '<span style="color: red;" >study Vue</span>' } } } </script>Copy the code

v-htmlDirective will update the inserted elementinnerHTML, i.e.,rawHtmlThe value of property is treated as<p>Insert child elements of the element:

If the rawHtml value contains other properties of the data object, then Vue will just insert it as normal HTML — ignoring the data binding in the parsing property value:

<template> <div> <p v-html="rawHtml"></p> </div> </template> <script> export default { data () { return { age: 18, rawHtml: '<span style="color: red;" < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; word-break: inherit! Important;"Copy the code

At this point,rawHtmlContains theageProperty will not be resolved:

Also, to avoid XSS attacks, use HTML interpolation only for trusted content and never for user-supplied content.

Binding HTML attribute

In development, there are often scenarios for data binding to HTML attributes. For example, the title attribute of the element shows different content according to different roles, which requires data binding of the title. Since the double-braced syntax does not apply to HTML attributes, the v-bind directive should be used in this case:

<div> <a href="www.xxx.com" v-bind:title="linkTitle"> Luffy </a> </div> </template> <script> export default {data () {return {linkTitle: 'Luffy is a character in One Piece'}}} </script>Copy the code

The V-bind directive binds the title attribute to the linkTitle Property in the data object. When the linkTitle Property changes, the title attribute will also change.

For cases where the HTML attribute is a Boolean, for example:

<button v-bind:disabled="isDisabled"> Button </button>Copy the code

ifisDisabledProperty is true, thendisabledAttribute will appear in<button>Element, and the button is disabled:

On the other hand, ifisDisabledThe value of property is false, such as yesnull,undefined,falseEquivalent, sodisabledAttribute does not appear in<button>The element:

Using JavaScript expressions

In addition to binding simple property keys in template data binding, Vue provides full JavaScript expression support, but each binding can only contain a single expression:

<div>{{ n + 10 }}</div>
<div>{{ isDisabled ? 'yes' : 'ok' }}</div>
<div>{{ message.split('').reverse().join('') }}</div>
<div v-bind:id="'list-' + id"></div>
Copy the code

The above expression is parsed as JavaScript in the scope of the owning Vue instance data.

instruction

Directives are special attributes with a V-prefix, and the value of the directive attribute is expected to be a single JavaScript expression (except for V-for). The syntax of a directive is: V-directive name: parameter. The modifier = value, for example, the event instruction V-on can be written like this:

<template>
  <div v-on:click.stop="add"></div>
</template>
Copy the code

Where v-on is the directive to bind the event listener, click is the argument, stop is the modifier, and add is the corresponding value. Some directives can be used without arguments and modifiers, such as v-pre:

</div> </template> <div v-pre>Copy the code

Some directives can be used without a value, such as V-on :click. Prevent:

<a href="https://www.baidu.com" v-on:click. Prevent > </a> </template>Copy the code

When the value of an expression changes, the effect of the expression is applied to the DOM in response:

<div v-if="visible">You can see it</div>
Copy the code

The V-if directive inserts or removes

elements based on whether the value of expression visible is true or false.
parameter

Some Vue directives can take an argument, which is represented by a colon after the instruction name. For example, use the V-bind directive to bind an HTML attribute:

<img v-bind:src="logoUrl" alt="logo">
Copy the code

SRC is the argument that tells v-bind to bind the SRC attribute of the element to the value of the expression logoUrl.

You can also use the V-on directive to bind event listeners, such as the focus event listening for the element:

<input v-on:focus="handleInput" type="text">
Copy the code

In the above code, the focus event name is the parameter.

In addition to the arguments defined at the outset, Vue also provides dynamic arguments — JavaScript expressions enclosed in square brackets as arguments to a directive:

<img v-bind:[name] ="logoUrl" alt="logo">
Copy the code

The name is the dynamic parameter, which is evaluated dynamically as a JavaScript expression, and the resulting value is used as the final parameter. For example, if the value of the name property is href, then this binding is equivalent to v-bind:href. When using dynamic parameters, there are the following constraints:

  • A constraint on the value of a dynamic parameter, which is expected to be evaluated as a string, or null in the exception case (which can be used explicitly to remove the binding). Any other value that is not a string will trigger a warning.

  • Syntax constraints on dynamic parameter expressions:

    • Dynamic parameter expressions cannot contain Spaces or quotes, because they are invalid in HTML attributes and trigger a compilation warning:

      <! -- This will trigger a compile warning -->
      <! Do not use Spaces or quotes in expressions. Or use computed attributes instead of such complex expressions -->
      <img v-bind:['a'+b] ="logoUrl" alt="logo">
      Copy the code
    • Dynamic parameters written directly in an HTML template should be named without uppercase characters, because browsers will force all HTML attributes to lowercase:

      <img v-bind:[attributeName] ="logoUrl" alt="logo">
      Copy the code

      In the above code, the browser will force the dynamic parameter to lowercase: v-bind:[Attributename]. If the current Vue instance does not have a property named Attributename, Vue will report the following error :[Vue warn]: Property or method “attributename” is not defined on the instance but referenced during render… .

The modifier

Modifiers are special suffixes after arguments that indicate that an instruction should be bound in a particular way. Such as:

<a v-on:click.prevent="onSubmit">Link to A</a>
Copy the code

In this case,.prevent is the modifier, which tells the V-on directive that it should call event.preventDefault() on click events that are triggered to prevent the default behavior.

So what are the modifiers? Depending on the instruction, the corresponding modifier is as follows:

  • v-onThe modifiers supported by an instruction are event modifiers, button modifiers, and system modifiers.
    • Event modifier:.stop,.prevent,.capture,.self,.once,.passive.
    • Key modifier:.enter,.tab,.esc,.selfdeleteAnd so on.
    • Key modifier:.ctrl,.shift,.left,.rightAnd so on.
  • v-bindThe modifiers supported by the directive are:.prop,.camel,.sync.
  • v-modelThe modifiers supported by the directive are:.lazy,.number,.trim.
abbreviations

Vue provides specific abbreviations for two commonly used instructions: V-bind and V-ON:

  • V – short for bind

    <! -- Complete syntax -->
    <img v-bind:src="logoUrl" alt="logo">
    
    <! -- Abbreviation grammar -->
    <img :src="logoUrl" alt="logo">
    
    <! -- Dynamic parameter abbreviation syntax -->
    <img :[key] ="logoUrl" alt="logo">
    Copy the code
  • V – on abbreviation

    <! -- Complete syntax -->
    <button v-on:click="doSomething">button</button>
    
    <! -- Abbreviation grammar -->
    <button @click="doSomething">button</button>
    
    <! -- Dynamic parameter abbreviation syntax -->
    <button@ [event] ="doSomething">button</button>
    Copy the code