Vue3相关有用信息


模板语法

文本插值​

  • 最基本的数据绑定形式是文本插值,它使用的是”Mustache”语法 (即双大括号):
    1
    <span>Message: {{ msg }}</span>
  • 双大括号标签会被替换为相应组件实例中 msg 属性的值。同时每次 msg 属性更改时它也会同步更新。

Attribute 绑定

  • 双大括号不能在 HTML attributes 中使用。想要响应式地绑定一个 attribute,应该使用 v-bind 指令:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <script setup>
    import { ref } from 'vue'

    const titleClass = ref('title')
    </script>

    <template>
    <!--
    h1中:class="titleClass"指向script中的const titleClass = ref('title')
    进而指向css中的.title
    -->
    <h1 :class="titleClass">Make me red</h1>
    <!--
    div v-bind:id="dynamicId"
    可以简写为
    div :id="dynamicId"
    -->
    </template>

    <style>
    .title {
    color: red;
    }
    </style>
  • v-bind 指令指示 Vue 将元素的 id attribute 与组件的 dynamicId 属性保持一致。如果绑定的值是 null 或者 undefined,那么该 attribute 将会从渲染的元素上移除。