Vue3 template syntax

Vue uses an HTML based template syntax that allows developers to declaratively bind the DOM to the data of the underlying Vue instance.

The core of Vue is a system that allows you to declaratively render data into DOM using concise template syntax.

Combined with the response system, when the application state changes, Vue can intelligently calculate the minimum cost of re rendering components and apply it to DOM operation.

interpolation

text

The most common form of data binding is text interpolation using {{...}} (double braces):

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="hello-vue" class="demo">
  {{ message }}
</div>

<script>
const HelloVueApp = {
  data() {
    return {
      message: 'Hello Vue!!'
    }
  }
}

Vue.createApp(HelloVueApp).mount('#hello-vue')
</script>
</body>

The content of the {{...}} tag will be replaced with the value of the message attribute in the corresponding component instance. If the value of the message attribute changes, the content of the {{...}} tag will also be updated.

If you do not want to change the content of the label, you can perform one-time interpolation by using the v-once instruction. When the data changes, the content at the interpolation will not be updated.

<span v-once>This will not change: {{ message }}</span>

Html

Use the v-html instruction to output HTML code:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="example1" class="demo">
    <p>Text interpolation using double braces: {{ rawHtml }}</p>
    <p>use v-html instructions: <span v-html="rawHtml"></span></p>
</div>

<script>
const RenderHtmlApp = {
  data() {
    return {
      rawHtml: '<span style="color: red">Red will be displayed here!</span>'
    }
  }
}

Vue.createApp(RenderHtmlApp).mount('#example1')
</script>
</body>

attribute

v-bind is a vue instruction used to bind html attributes, as follows:

<div id="app">
    <p v-bind:title="title">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>
......
var vm = new Vue({
    el: '#app',
    data: {
        title: 'title content'
    }
});

The html here will finally be rendered as:

<div id="app">
    <p title="title content">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>

The above v-bind is also our initial understanding of the vue instruction, but in fact, the expected value of the vue instruction (for example, in v-bind:class = "classProperty", v-bind is the instruction, the following class is the parameter, and classProperty is called the "expected value" in the official document), in addition to binding a string type variable as above, In fact, it supports a single JavaScript expression (except v-for).

So here, we can have more choices, such as:

Perform operations

<div id="app">
    <p v-bind:title="t1 + ' ' + t2">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>
......
var vm = new Vue({
    el: '#app',
    data: {
        t1: 'title1',
        t2: 'title2'
    }
});

Last rendered result:

<div id="app">
    <p title="title1 title2">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>

Execute functions, etc

<div id="app">
    <p v-bind:title="getTitle()">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>
......
var vm = new Vue({
    el: '#app',
    data: {
        getTitle: function () {
            return 'title content';
        }
    }
});

Last rendered result:

<div id="app">
    <p title="title content">html Property cannot be bound in double curly braces, only v-bind instructions</p>
</div>

Supported data types

In the above content, the expected value of the instruction is string type data, but in fact, we know that js has many data types. What if it is put into it?

object type

<div id="app">
    <p v-bind:title="obj">content</p>
</div>
......
var obj = {};
var vm = new Vue({
    el: '#app',
    data: {
        obj: obj
    }
});

Why do you choose the object type as soon as you come? The answer is that it is representative, and its rendering results are as follows:

<div id="app">
    <p title="[object Object]">content</p>
</div>

Well, why does this look familiar? Kind of... Yeah! Return value of toString method of object! In order to verify our conjecture, we conduct further tests:

<div id="app">
    <p v-bind:title="obj">content</p>
</div>
......
var obj = {};
 
obj.toString = function () {
    return 'edited in toString!';
};
 
var vm = new Vue({
    el: '#app',
    data: {
        obj: obj
    }
});

The toString method of obj has been modified here (but to be exact, this is not modification, but addition. At the beginning, there is no toString method on the obj Object, which inherits Object.prototype.toString, but here we execute obj.toString = function... In fact, we add a toString method to it, so that when it executes, it does not need to call the method inherited from Object.), The rendering result is as follows:

<div id="app">
    <p title="edited in toString!">content</p>
</div>

This further confirms our conjecture.

Array type

The toString method of array type is different from that of object type. It will return the same result as executing arr.join(','). Such as [1, 2, 3] Tostring() will return "1,2,3". Test as follows:

<div id="app">
    <p v-bind:title="arr">content</p>
</div>
......
var vm = new Vue({
    el: '#app',
    data: {
        arr: [1, 2, 3]
    }
});

The rendering result is as follows:

<div id="app">
    <p title="1,2,3">content</p>
</div>

Still the same as expected.

Other types

  • Number type, toString is executed normally, including the number 0, and the results are rendered into the corresponding string normally;
  • boolean type. True is normally rendered as the string "true", but false. Although the toString method will return "false"
    String, but it is not rendered;
  • null / undefined types, both of which have no toString method and are not rendered.

Obviously, before the toString method is executed, vue should perform type verification internally and output only when the conditions are met. Moreover, this is not a simple true / false value verification, because although and 0 are false values, they are finally rendered like true values. How to implement it may need to refer to the source code of vue, which will not be studied here.

The following examples judge the value of use. If it is true, use the style of class1 class, otherwise do not use this class:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
.class1{
  background: #444;
  color: #eee;
}
</style>
</head>
<body>
<div id="app">
  <label for="r1">Modify color</label><input type="checkbox" v-model="use" id="r1">
  <br><br>
  <div v-bind:class="{'class1': use}">
    v-bind:class instructions
  </div>
</div>

<script>
const app = {
  data() {
    return {
      use: false
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>
</body>

expression

Vue.js provides full JavaScript expression support.

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    {{5+5}}<br>
    {{ ok ? 'YES' : 'NO' }}<br>
    {{ message.split('').reverse().join('') }}
    <div v-bind:id="'list-' + id">Rookie tutorial</div>
</div>
    
<script>
const HelloVueApp = {
  data() {
    return {
      ok: true,
      message: 'RUNOOB!!',
      id: 1
    }
  }
}
 
Vue.createApp(HelloVueApp).mount('#app')
</script>
</body>

The expression will be parsed as JavaScript under the data scope of the current active instance. One limitation is that each binding can only contain a single expression, so the following examples will not take effect:

<!--  This is a statement, not an expression:-->
{{ var a = 1 }}

<!-- Flow control will not take effect, please use ternary expression -->
{{ if (ok) { return message } }}

instructions

Instructions are special attributes with a v-prefix.

Directive is used to apply certain behaviors to the DOM when the value of an expression changes. Examples are as follows:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    <p v-if="seen">Now you see me</p>
</div>
    
<script>
const app = {
  data() {
    return {
      seen: true /* If it is changed to false, the information cannot be displayed */
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>
</body>

Here, the v-if instruction will decide whether to insert the p element according to the value of the expression see (true or false).

What is the main purpose of the v-if attribute? What is its purpose?

There are generally two scenarios for using v-if:

  • Multiple elements show or hide an element or multiple elements through conditional judgment
  • Switch between two views

Two examples are written below, which are simple examples of Vue official.

  • The first example realizes the display of three elements, A, B and C, in which type is equal to different values.
  • In the second example, click the button to switch between two views.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue in v-if Common use of</title>
    <script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
</head>
<script>
window.onload = function(){

    //Create a vue instance
    var app = new Vue({
        el: '#app',
        data: {
            type:'C',
            loginType:'username'
        },
        methods:{
            changeloginType(){
                let self = this;
                if(self.loginType=='username'){
                    self.loginType = ''
                }else{
                    self.loginType = 'username'
                }
            }
        }
    })
}

</script>
<body>
    <div id="app">
        <div style="color:red">v-if Simple and practical</div>
        <template>
            <div v-if="type == 'A'">
                A
            </div>
            <div v-else-if="type=='B'">
                B
            </div>
            <div v-else>
                C
            </div>
        </template>
        <div style="color:green">v-if Pop up switch</div>
        <template v-if="loginType === 'username'">
            <label>user name:</label>
            <input placeholder="Enter your username" key="username-input">
        </template>
        <template v-else>
            <label>password:</label>
            <input placeholder="Enter your email address" key="email-input">
        </template>
        <button @click="changeloginType">Switching state</button>
    </div>
</body>
</html>

design sketch:

There are many other instructions, each with special functions. For example, the v-for instruction can bind the data of the array to render a list of items:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
  <ol>
    <li v-for="site in sites">
      {{ site.text }}
    </li>
  </ol>
</div>
<script>
const app = {
  data() {
    return {
      sites: [
        { text: 'Google' },
        { text: 'Runoob' },
        { text: 'Taobao' }
      ]
    }
  }
}

Vue.createApp(app).mount('#app')
</script>
</body>

parameter

Parameters are indicated by a colon after the instruction. For example, the v-bind instruction is used to update HTML attributes in response:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    <p><a v-bind:href="url">Rookie tutorial</a></p>
</div>
    
<script>
const HelloVueApp = {
  data() {
    return {
      url: 'https://www.runoob.com'
    }
  }
}
 
Vue.createApp(HelloVueApp).mount('#app')
</script>
</body>

Here, href is a parameter that tells the v-bind instruction to bind the href attribute 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:

<!-- Complete grammar -->
<a v-on:click="doSomething"> ... </a>

<!-- abbreviation -->
<a @click="doSomething"> ... </a>

<!-- Abbreviations for dynamic parameters (2.6.0+) -->
<a @[event]="doSomething"> ... </a>

Here, the parameter is the event name to listen to.

Modifier

The modifier is a half angle period Indicates the special suffix used to indicate that an instruction should be bound in a special way. For example The prevent modifier tells the v-on instruction to call event for the triggered event preventDefault():

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

User input

In the input box, we can use the v-model instruction to realize bidirectional data binding:

<title>Vue Test example - Rookie tutorial(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    <p>{{ message }}</p>
    <input v-model="message">
</div>

<script>
const app = {
  data() {
    return {
      message: 'Runoob!'
    }
  }
}

Vue.createApp(app).mount('#app')
</script>
</body>

The v-model instruction is used to create two-way data binding on form control elements such as input, select, textarea, checkbox and radio, and automatically update the value of the bound element according to the value on the form.

For button events, we can use v-on to listen for events and respond to user input.

The following example reverses the string after the user clicks the button:

<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">Reverse string</button>
</div>
    
<script>
const app = {
  data() {
    return {
      message: 'Runoob!'
    }
  },
  methods: {
    reverseMessage() {
      this.message = this.message
        .split('')
        .reverse()
        .join('')
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>
</body>

abbreviation

v-bind abbreviation

Vue.js provides special abbreviations for the two most commonly used instructions:

<!-- Complete grammar -->
<a v-bind:href="url"></a>
<!-- abbreviation -->
<a :href="url"></a>

v-on abbreviation

<!-- Complete grammar -->
<a v-on:click="doSomething"></a>
<!-- abbreviation -->
<a @click="doSomething"></a>

Keywords: Vue

Added by GateGuardian on Fri, 04 Mar 2022 11:24:08 +0200