Vue 基础语法
Vue 的模板语法是基于标准 HTML 的。这意味着所有的 Vue 模板都是有效的 HTML,可以被所有标准的浏览器解析。在其内部,Vue 将模板编译成高效的、虚拟 DOM 的渲染函数。结合响应式系统,当应用状态改变时,Vue 能够智能地计算出需要重新渲染的最小组件集,并以最少的操作来更新 DOM。
文本插值 (Text Interpolation)
最基本的数据绑定形式是文本插值,它使用“Mustache”语法(双大括号):
vue
<script setup>
import { ref } from 'vue'
const msg = ref('Hello Vue!')
</script>
<template>
<span>Message: {{ msg }}</span>
</template>双大括号里的内容会被替换为 msg 变量的值。当 msg 的值改变时,这部分内容也会自动更新。
你还可以在双大括号内使用任何有效的单个 JavaScript 表达式:
vue
<script setup>
const number = ref(10)
</script>
<template>
<p>计算结果: {{ number + 1 }}</p>
<p>三元表达式: {{ number > 5 ? 'Yes' : 'No' }}</p>
</template>原始 HTML
双大括号会将数据解释为普通文本,而不是 HTML。为了输出真正的 HTML,你需要使用 v-html 指令:
vue
<script setup>
import { ref } from 'vue'
const rawHtml = ref('<span style="color: red">This should be red.</span>')
</script>
<template>
<p>Using text interpolation: {{ rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>
</template>安全警告:在你的网站上动态渲染任意的 HTML 是非常危险的,因为它很容易导致 XSS(跨站脚本)攻击。请只在内容完全受你信任的情况下使用 v-html,绝不要将用户提供的内容用 v-html 来渲染。
属性绑定 (Attribute Binding)
双大括号语法不能在 HTML 属性 (attributes) 中使用。为了给属性绑定动态值,我们需要使用 v-bind 指令:
vue
<script setup>
import { ref } from 'vue'
const elementId = ref('my-element')
const isDisabled = ref(true)
</script>
<template>
<div v-bind:id="elementId">这是一个有动态 ID 的 div。</div>
<button v-bind:disabled="isDisabled">一个被禁用的按钮</button>
</template>因为 v-bind 非常常用,所以它有一个专门的简写语法,就是一个冒号 (:):
vue
<template>
<div :id="elementId">...</div>
<button :disabled="isDisabled">...</button>
</template>使用 JavaScript 表达式
对于所有的数据绑定,Vue 都支持完整的 JavaScript 表达式能力。这意味着你可以在模板中进行计算、调用方法等。
vue
<script setup>
const person = {
name: 'John Doe',
age: 30
}
function toUpperCase(str) {
return str.toUpperCase()
}
</script>
<template>
<p>{{ person.name.split('').reverse().join('') }}</p>
<p>{{ toUpperCase('hello') }}</p>
</template>限制:每个绑定只能包含一个单独的表达式。像 let a = 1 这样的语句是无效的。此外,表达式的访问范围被限制在当前组件实例的属性和方法上,不能访问全局变量。