Home > Web Front-end > Vue.js > How to use Vue3's template syntax?

How to use Vue3's template syntax?

WBOY
Release: 2023-05-10 09:34:16
forward
1249 people have browsed it

1. What is template syntax?

We can directly understand the template syntax of Vue.js as an extension of the HTML syntax, including all its template node declarations, attribute settings and event registrations. etc. are designed to be extended according to the syntax of HTML. According to the official statement, "all Vue templates are syntactically legal HTML and can be parsed by browsers and HTML parsers that comply with the specification."

Vue uses an HTML-based template syntax that allows us to declaratively bind the data of its component instances to the rendered DOM

2. Content Rendering instructions

1. v-text

Use the v-tex t instruction to fill the empty elements with data in plain text

// 组合式
<script setup>

    import { reactive } from &#39;vue&#39;

    let student = reactive({
        name: &#39;Jack&#39;,
        desc: &#39;<h4>我是来自中国的小朋友!</h4>&#39;
    })
    
</script>

<template>

  <!-- 使用v-text指令,将数据采用纯文本方式填充其空元素中 -->
  
  <div v-text="student.name"></div>

  <!-- v-text:以纯文本的方式显示数据 -->
  <div v-text="student.desc"></div>

  <!-- 下面的代码会报错:div 元素不是空元素 -->
  <!-- <div v-text="student.name">这是原始的div数据</div> -->
   
</template>
Copy after login

2. {{ }} interpolation expression

Render data as plain text at a certain position in the element

// 组合式
<script setup>

import { reactive } from &#39;vue&#39;

let student = reactive({
    name: &#39;Jack&#39;,
    desc: &#39;<h4>我是来自中国的小朋友!</h4>&#39;
})

</script>

<template>

    <!-- 插值表达式:在元素中的某一位置采用纯文本的方式渲染数据 -->
    <div>这是一个 DIV 元素,{{ student.name }},{{ student.desc }}</div>

</template>
Copy after login

3. v-html

Usev-html instruction, fill the empty elements with data using HTML syntax

// 组合式
<script setup>

import { reactive } from &#39;vue&#39;

let student = reactive({
    name: &#39;Jack&#39;,
    desc: &#39;<h4>我是来自中国的小朋友!</h4>&#39;
})


</script>

<template>

    <!-- 使用v-html指令,将数据采用HTML语法填充其空元素中 -->

    <div v-html="student.name"></div>

    <!-- v-html:以 HTML 语法显示数据 -->
    <div v-html="student.desc"></div>

    <!-- 下面的代码会报错:div 元素不是空元素 -->
    <!-- <div v-html="student.name">这是原始的div数据</div> -->

</template>
Copy after login

3. Two-way binding instruction

1. v-model

v-model Two-way data binding instructions, view data and data source synchronization<br/>Generally, v-model instructions are used in form elements:

  • The and