1.插值语法
vue模板里可以使用插值语法渲染数据,其中,插值语法里可以写表达式、数值运算、api操作。
<template>
<h1>{{ message }}</h1>
<h1>{{ message.split("").reverse().join("") }}</h1>
</template>
<script setup lang="ts">
const message: string = "Hello Vue 3 + Vite";
</script>
2.v-text,v-html
可以在标签中添加v-text,将数据绑定到元素的文本内容上,标签中添加v-html,将数据绑定到元素的innerHTML上。
<template>
<h1 v-text="message"></h1>
<div v-html="innerHTML"></div>
</template>
<script setup lang="ts">
const message: string = "Hello Vue 3 + Vite";
const innerHTML: string = "<h1>This is innerHTML</h1>";
</script>
3.v-if VS v-show
v-if是 "真正"的条件渲染。它会确保在切换过程中,条件块内的元素被适当地创建或销毁。
v-show是 "基于 CSS"的条件显示。无论条件是什么,元素始终会被渲染,只是简单地用 CSSdisplay属性来切换显示或隐藏。
<template>
<h1 v-if="show">v-if渲染{{ message }}</h1>
<h1 v-show="show">v-show渲染{{ message }}</h1>
</template>
<script setup lang="ts">
const show: boolean = false;
const message: string = "Hello Vue 3 + Vite";
</script>
通过控制台检查元素,发现v-if条件下的标签被注释掉了,而v-show条件下的标签则是添加了display:none的样式。
在初始渲染的开销上来说v-if较低,切换渲染的开销则是v-show较低。
4.v-for循环渲染
<template>
<ul>
<li v-for="fruit in arr">{{ fruit }}</li>
</ul>
</template>
<script setup lang="ts">
const arr: string[] = ["apple", "banana", "orange"];
</script>
5.v-on,v-bind
v-on:事件绑定,简写为@事件名,可以用修饰符控制事件的触发条件,如:@click.stop。v-bind:属性绑定,简写为:属性名,若属性里有多个值,用数组表示,如::class="['btn', 'active']"。
<template>
<button @click="handleClick" :class="show ? 'btn' : ''">Click me</button>
</template>
<script setup lang="ts">
const show: boolean = true;
const handleClick = () => {
console.log("点击事件");
};
</script>
<style scoped>
.btn {
font-family: "Roboto", sans-serif;
background: linear-gradient(to right, #4facfe, #00f2fe);
color: #fff;
padding: 10px 20px;
border: none;
transition: all 0.3s ease;
}
</style>
6.v-model
双向数据绑定,可以绑定input、select、textarea等元素的value值。
<template>
<input type="text" v-model="message" />
<h2>{{ message }}</h2>
</template>
<script setup lang="ts">
import { ref } from "vue";
const message = ref("Hello Vue 3 + Vite");
</script>
在input里修改message的值,h2标签里的值也会改变。
7.v-once,v-memo
v-once和v-memo都是 Vue 中用于性能优化的指令。它们的核心目标都是减少不必要的渲染开销,但它们的工作方式和使用场景有很大不同。
| 特性 | v-once | v-memo |
|---|---|---|
| 目的 | 渲染一次,永不更新 | 有条件地跳过更新 |
| 机制 | 渲染后标记为静态内容 | 比较依赖项数组 |
| 灵活性 | 低(全开,全关) | 高(由依赖项数组控制) |
| 语法 | v-once(无参数) | v-memo = "[val1,val2]" |
| 场景 | 纯静态内容 | v-for长列表,昂贵组件 |
参考文章
小满zs 学习Vue3 第四章(模板语法 & vue指令) xiaoman.blog.csdn.net/article/det…