Vue3 template syntax – attributes, expressions, directives, parameters, modifiers, user input, abbreviations

Article directory

  • Vue3 template syntax – attributes, expressions, directives, parameters, modifiers, user input, abbreviations
    • 1. Concept
    • 2. Interpolation
      • 2.1 Text
      • 2.2 HTML
    • 3. Properties
    • 4. Expression
    • 5. Instructions
    • 6. Parameters
    • 7. Modifiers
    • 8. User input
    • 9. v-on command monitoring
    • 10. Abbreviations

Vue3 template syntax – attributes, expressions, instructions, parameters, modifiers, user input, abbreviations

1. Concept

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 the 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 the component. And applied to DOM operations.

2. Interpolation

2.1 Text

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

  • The content of the {{...}} tag will be replaced by the value of the message attribute in the corresponding component instance. If the value of the message attribute When changes occur, the content of the {{...}} tag will be updated.

  • Note: If you do not want to change the content of the tag, you can perform one-time interpolation by using the v-once command. When the data changes, the content at the interpolation is not updated.

    The main advantage of the once directive is that it can effectively reduce the number of renderings of components and improve page rendering performance. Especially for static content that does not require responsive updates, using the v-once directive can greatly reduce the stress on the browser, thereby improving the user experience.

     For example, in the product list of an e-commerce website, the title, price and other information displayed for each product are relatively stable and do not need to be changed frequently. At this time, you can use the v-once command to Reduce the number of page renderings and improve page rendering efficiency.
    
    <script setup>
    import {<!-- -->ref} from "vue"
    
    const count = ref(0)
    
    setInterval(() => {<!-- -->
      count.value++
    }, 1000)
    </script>
    
    <template>
      <span v-once>Make it never update: {<!-- -->{ count }}</span>
    </template>
    

    The v-once directive is applied to the span tag, so that the content in this tag will only be rendered once and will not be updated as the data changes, while the content data can be updated responsively.

  • It should be noted that v-once can only be applied to deterministic templates and cannot be used in components containing dynamic templates such as loops or conditional statements, otherwise it may cause unexpected results.

2.2 HTML

  • Use v-html directive to output html code
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Vue test example v-html directive is used to output html code</title>
    <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
</head>
<body>
<!--Create a div with the ID app class and demo-->
<div id="app" class="demo">
    <p>Text interpolation using double curly braces: {<!-- -->{ rawHtml }}</p>
    <p>Use the V-html command to output html code: <span v-html="rawHtml"></span></p>
</div>

<script>
    // Define Vue3's RenderHtmlApp application
    const RenderHtmlApp = {<!-- -->
        //Set the return value to a list
        data() {<!-- -->
            return {<!-- -->
                rawHtml: '<span style="color: red">Red will be displayed here! ! ! </span>'
            }
        }
    }

    //Create the RenderHtmlApp application, mount('#app') to mount the Vue application RenderHtmlApp into <div id="app" class="demo">
    Vue.createApp(RenderHtmlApp).mount('#app')
</script>
</body>
</html>


Page effect: Using {{ }} text interpolation will directly display the entire html tag on the page. Using v-html will directly display the content in the html tag.

3. Properties

  • Values in HTML attributes should use the v-bind directive. v-bind: can bind data to HTML element attributes

    <div v-bind:id="dynamicId"></div>
    
  • For Boolean properties, the normal values are true or false; if the property value is null or undefined, the property is not displayed.

    <button v-bind:disabled="isButtonDisabled">Button</button>
    
  • The following example determines the value of use. If it is true, use the style of class1 class, otherwise do not use this class.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Vue test example v-bind data binding to HTML element attributes</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
        <style>
            .class1{<!-- -->
                background: #444;
                color: #eee;
            }
        </style>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
    <!-- Create an input box with ID r1 and checkbox type, and use the v-model directive to implement two-way binding of form data
    Create a label label and use the for attribute to specify the input box with associated id="r1"
    -->
        <label for="r1">Modify color</label><input type="checkbox" v-model="use" id="r1">
        <br><br>
    <!-- Create a div in the div with the ID of app. Use v-bind to bind the data to the class attribute of html. Determine the value of use. If it is true, use the style of class1 class, otherwise do not use this class -->
        <div v-bind:class="{'class1': use}">
            v-bind:class directive
        </div>
    
    </div>
    
    <script>
        // Define the HelloVueApp application of Vue3
        const HelloVueApp = {<!-- -->
            //Set the return value message. The default value is false.
            data() {<!-- -->
                return {<!-- -->
                    use: false
                }
            }
        }
        //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
        Vue.createApp(HelloVueApp).mount('#app')
    </script>
    </body>
    </html>
    

    Page effect: Click to select


4. Expression

Vue.js provides full JavaScript expression support.

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

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

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

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Vue test examples Vue.js provide full JavaScript expression support</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
        <p>{<!-- -->{ 5 + 5 }}</p>
        <p>{<!-- -->{ ok ? 'YES' : 'NO'}}</p>
        {<!-- -->{ message.split('').reverse().join('') }}<br>
        <div v-bind:id="'list-' + id">v-bind data is bound to HTML element attributes</div>
    </div>
    
    <script>
        // Define the HelloVueApp application of Vue3
        const HelloVueApp = {<!-- -->
            //Set the return value message. The default value is false.
            data() {<!-- -->
                return {<!-- -->
                    OK: true,
                    message: 'RUNOOB!!!',
                    id:1
                }
            }
        }
        //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
        Vue.createApp(HelloVueApp).mount('#app')
    </script>
    </body>
    </html>
    

    Page effect:

5. Command

  • Directives are special attributes prefixed with v-.

    Directives are used to apply certain behavior to the DOM when the value of an expression changes. Examples below:

  • v-if directive: Determine whether to insert the p element based on the value of the expression seen (true or false)

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Vue test instance directive is a special attribute with v- prefix, which is used to apply certain behaviors to the DOM when the value of the expression changes</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
       <p v-if="seen">Now you see me! ! !</p>
    </div>
    
    <script>
        // Define the HelloVueApp application of Vue3
        const HelloVueApp = {<!-- -->
            //Set the return value message. The default value is false.
            data() {<!-- -->
                return {<!-- -->
                    // If changed to false, the information cannot be displayed.
                    seen: true
                }
            }
        }
        //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
        Vue.createApp(HelloVueApp).mount('#app')
    </script>
    </body>
    </html>
    

    Page effect:


  • v-for directive: You can bind array data to render a list of items

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Vue test example v-for instruction loops to render elements or components based on the attribute values of the array, which is equivalent to the for loop in Java</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
        <!-- The v-for instruction loops to render elements or components based on the attribute values of the array. It is equivalent to the for loop in Java.
        The v-for directive can bind array data to render a list of items
        Loop to display the returned list on the page
        ol defaults to an ordered list, ul defaults to an unordered list -->
       <ol>
           <li v-for="site in sites" key="site.id">
    <!-- Equivalent to traversing items using item.id-->
               {<!-- -->{ site.text }}
           </li>
       </ol>
    </div>
    
    <script>
        // Define the HelloVueApp application of Vue3
        const HelloVueApp = {<!-- -->
            //Set the return value to a list
            data() {<!-- -->
                return {<!-- -->
                   sites: [
                       {<!-- --> id: 1, text: 'GOOGLE'},
                       {<!-- --> id: 2, text: 'RUNOOB'},
                       {<!-- --> id: 3, text: 'Taobao'}
                   ]
                }
            }
        }
    
        //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
        Vue.createApp(HelloVueApp).mount('#app')
    </script>
    </body>
    </html>
    

    Page effect:

  • Expanded subtotal: The difference between ul and ol and experience summary

    ul is an unordered list: the most common list in web pages. There is a parallel relationship between each list item. There is no order level, such as navigation bar, news Topic display areaetc. The default example looks like (with filled circles by default):

     <ul>
          <li>Unordered list item 1</li>
          <li>Unordered list item 2</li>
          <li>Unordered list item 3</li>
      </ul>
    

    ol is an ordered list: Each list item will be arranged in a certain order, such as game rankings, song rankings, etc. that are common on web pages. The default example looks like (with numbers by default):

     <ol>
          <li>Ordered list item 1</li>
          <li>Ordered list item 2</li>
          <li>Ordered list item 3</li>
      </ol>
    

    You can modify the starting number of the ordered list from (default 1 to 2)

    <ol start="2">
        <li>Ordered list item 1</li>
        <li>Ordered list item 2</li>
        <li>Ordered list item 3</li>
    </ol>
    

6. Parameters

  • Parameters are specified with a colon after the command. For example, the v-bind directive is used to update HTML attributes responsively, where href is a parameter that tells the v-bind directive to bind the element’s href attribute to the value of the expression url.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Vue test example v-bind data binding to HTML element attributes</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
    <!-- Use the v-bind directive to bind hyperlinks -->
        <p><a v-bind:href="url">V-bind binding hyperlink</a></p>
    </div>
    
    <script>
        // Define the HelloVueApp application of Vue3
        const HelloVueApp = {<!-- -->
            //Set the return value message
            data() {<!-- -->
                return {<!-- -->
                    url: 'https://static.runoob.com/images/code-icon-script.png'
                }
            }
        }
        //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
        Vue.createApp(HelloVueApp).mount('#app')
    </script>
    </body>
    </html>
    

    Page effect: Click on the hyperlink to enter the hyperlink page


  • Another example is the v-on directive, which is used to listen to DOM events: here the parameter is the name of the event to be listened to. Examples at

    <!-- Complete syntax -->
    <a v-on:click="doSomething"> ... </a>
    
    <!-- Abbreviation -->
    <a @click="doSomething"> ... </a>
    
    <!-- Abbreviation for dynamic parameters (2.6.0 + ) -->
    <a @[event]="doSomething"> ... </a>
    

7. Modifiers

  • Modifiers are special suffixes specified with a period . that indicate that a directive should be bound in a special way. For example, the .prevent modifier tells the v-on directive to call event.preventDefault() for the triggered event:

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

8. User input

In the input input box, we can use the v-model directive to implement two-way data binding.

v-model command: used to create two-way data binding on form control elements such as input, select, textarea, checkbox, radio, etc., and automatically update the bound elements based on the values on the form. value.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue test example - In the input input box, we can use the v-model directive to implement two-way data binding</title>
    <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
</head>
<body>
<!--Create a div with the ID app class and demo-->
<div id="app" class="demo">
<!-- Create an input box in the div and bind the message in the application in Vue3 to the text input box -->
    <p>{<!-- -->{ message }}</p>
    <input type="text" v-model="message">
</div>

<script>
// Define the HelloVueApp application of Vue3
const HellVueApp = {<!-- -->
    //Set the return value message
    data() {<!-- -->
        return {<!-- -->
            message: 'Runoob!'
        }
    }
}

//Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
Vue.createApp(HellVueApp).mount('#app')
</script>

</body>
</html>

Page effect:

9. v-on command monitoring

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

  • Another example is the v-on directive, which is used to listen to DOM events: here the parameter is the name of the event to be listened to

    <!-- Complete syntax -->
    <a v-on:click="doSomething"> ... </a>
    
    <!-- Abbreviation -->
    <a @click="doSomething"> ... </a>
    
    <!-- Abbreviation for dynamic parameters (2.6.0 + ) -->
    <a @[event]="doSomething"> ... </a>
    
  • Click the button to reverse the string

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue test example - v-model directive is used in input, select, textarea, checkbox, radio, etc.
            Create two-way data binding on the form control element, and automatically update the value of the bound element according to the value on the form</title>
        <script src="//i2.wp.com/cdn.staticfile.org/vue/3.2.36/vue.global.min.js"></script>
    </head>
    <body>
    <!--Create a div with the ID app class and demo-->
    <div id="app" class="demo">
    <!-- Create an input box in the div and bind the message in the application in Vue3 to the text input box -->
        <p>{<!-- -->{ message }}</p>
        <button v-on:click="reverseMessage">Reverse string</button>
    </div>
    
    <script>
    // Define the HelloVueApp application of Vue3
    const HellVueApp = {<!-- -->
        //Set the return value message
        data() {<!-- -->
            return {<!-- -->
                message: 'Runoob!'
            }
        },
        methods: {<!-- -->
            // Click to reverse the string
            reverseMessage() {<!-- -->
                this.message = this.message.split('').reverse().join('')
            }
        }
    }
    
    //Create the HelloVueApp application, mount('#app') mount the Vue application HelloVueApp into <div id="app" class="demo">
    Vue.createApp(HellVueApp).mount('#app')
    </script>
    
    </body>
    </html>
    

    Page effect: Click the button string will be reversed

10. Abbreviations

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

  • v-bind abbreviation

    <!-- Complete syntax -->
    <a v-bind:href="url"></a>
    <!-- Abbreviation -->
    <a :href="url"></a>
    
  • v-on abbreviation

    <!-- Complete syntax -->
    <a v-on:click="doSomething"></a>
    <!-- Abbreviation -->
    <a @click="doSomething"></a>