Vue3中的常用指令詳解
在 Vue3 的世界里,指令是連接模板與邏輯的橋梁,它們以v-開頭,為我們提供了簡潔且強(qiáng)大的 DOM 操作與業(yè)務(wù)邏輯處理能力。今天,我們就來逐一剖析這些常用指令,帶你從入門到精通,讓前端開發(fā)效率 “飛” 起來。
一、文本與 HTML 渲染:v-text與v-html
1. v-text:純文本渲染
v-text的作用是將數(shù)據(jù)純文本式地插入到元素中,相當(dāng)于 JavaScript 中的element.textContent。它會覆蓋元素原本的內(nèi)容,且自動進(jìn)行 HTML 轉(zhuǎn)義,避免 XSS 攻擊。
<template>
<div v-text="message"></div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello, Vue3 指令!');
</script>渲染后,<div>中會直接顯示Hello, Vue3 指令!。
2. v-html:HTML 內(nèi)容渲染
若需要渲染包含 HTML 標(biāo)簽的內(nèi)容,v-html就派上用場了,它相當(dāng)于element.innerHTML。注意:使用時需確保內(nèi)容來源可信,否則易引發(fā) XSS 風(fēng)險(xiǎn)。
<template>
<div v-html="richContent"></div>
</template>
<script setup>
import { ref } from 'vue';
const richContent = ref('<strong>這是帶HTML標(biāo)簽的內(nèi)容</strong>');
</script>渲染后,<div>中會顯示加粗的 “這是帶 HTML 標(biāo)簽的內(nèi)容”。
二、條件渲染:v-if、v-else、v-else-if
這組指令用于根據(jù)條件動態(tài)創(chuàng)建或銷毀 DOM 元素,適合條件復(fù)雜或切換不頻繁的場景(因?yàn)?DOM 會真實(shí)增刪)。
基本用法
<template>
<div v-if="type === 'A'">類型A</div>
<div v-else-if="type === 'B'">類型B</div>
<div v-else>其他類型</div>
</template>
<script setup>
import { ref } from 'vue';
const type = ref('A');
</script>當(dāng)type變化時,對應(yīng)的<div>會被創(chuàng)建或銷毀。
與v-show的區(qū)別
很多同學(xué)會混淆v-if和v-show,這里做個對比:
| 指令 | 渲染機(jī)制 | 性能特點(diǎn) | 適用場景 |
|---|---|---|---|
| v-if | 動態(tài)增刪 DOM 元素 | 切換時開銷較大 | 條件不常切換、邏輯復(fù)雜的場景 |
| v-show | 控制display屬性顯隱 | 初始渲染開銷略大 | 頻繁切換的場景 |
v-show示例:
<template>
<div v-show="isVisible">我可以被頻繁切換顯隱</div>
</template>
<script setup>
import { ref } from 'vue';
const isVisible = ref(true);
</script>三、列表渲染:v-for
v-for用于循環(huán)渲染列表數(shù)據(jù),支持?jǐn)?shù)組、對象、字符串甚至數(shù)字的遍歷。
數(shù)組遍歷
<template>
<ul>
<li v-for="(item, index) in list" :key="index">
{{ index + 1 }}. {{ item.name }}
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const list = ref([
{ name: 'Vue指令' },
{ name: '組件化' },
{ name: '響應(yīng)式' }
]);
</script>key是為了讓 Vue 更高效地復(fù)用 DOM,建議使用唯一標(biāo)識(如 ID)而非索引。
對象與其他類型遍歷
(1)對象遍歷:v-for="(value, key, index) in obj"
(2)字符串遍歷:v-for="(char, index) in 'Vue'"
(3)數(shù)字遍歷:v-for="num in 3"(渲染 3 次)
四、事件與屬性綁定:v-on與v-bind
1. v-on:事件監(jiān)聽
用于給元素綁定事件,可簡寫為@。支持傳參、事件修飾符(如.stop、.prevent)等。
<template>
<button @click="handleClick('參數(shù)')">點(diǎn)擊我</button>
<form @submit.prevent="handleSubmit">
<button type="submit">提交</button>
</form>
</template>
<script setup>
const handleClick = (param) => {
console.log('點(diǎn)擊事件觸發(fā),參數(shù):', param);
};
const handleSubmit = () => {
console.log('表單提交(已阻止默認(rèn)行為)');
};
</script>2. v-bind:屬性綁定
用于綁定 HTML 屬性、組件 props 等,可簡寫為:。
<template>
<img :src="imgUrl" :alt="imgAlt" :class="{ active: isActive }">
<MyComponent :propsData="componentData" />
</template>
<script setup>
import { ref } from 'vue';
import MyComponent from './MyComponent.vue';
const imgUrl = ref('https://example.com/vue.png');
const imgAlt = ref('Vue Logo');
const isActive = ref(true);
const componentData = ref({ name: 'Vue指令詳解' });
</script>五、雙向數(shù)據(jù)綁定:v-model
v-model是語法糖,本質(zhì)是結(jié)合v-bind(綁定值)和v-on(監(jiān)聽輸入事件),實(shí)現(xiàn)表單元素與數(shù)據(jù)的雙向同步。
<template>
<input v-model="inputValue" type="text" placeholder="請輸入內(nèi)容">
<p>你輸入的內(nèi)容:{{ inputValue }}</p>
<!-- 自定義組件的v-model -->
<MyInput v-model="customValue" />
</template>
<script setup>
import { ref } from 'vue';
import MyInput from './MyInput.vue';
const inputValue = ref('');
const customValue = ref('自定義組件雙向綁定');
</script>在自定義組件中,v-model默認(rèn)綁定modelValue prop 和update:modelValue事件,也可通過model選項(xiàng)自定義。
六、插槽分發(fā):v-slot
v-slot(可簡寫為#)用于組件插槽的內(nèi)容分發(fā),讓組件更具擴(kuò)展性。
具名插槽
<!-- 父組件 -->
<template>
<Layout>
<template #header>
<h1>頁面頭部</h1>
</template>
<template #footer>
<p>頁面底部</p>
</template>
<template #default>
<p>頁面主體內(nèi)容</p>
</template>
</Layout>
</template>
<!-- Layout組件 -->
<template>
<div class="layout">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> <!-- 默認(rèn)插槽 -->
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>作用域插槽
若插槽內(nèi)容需要訪問子組件的數(shù)據(jù),可使用作用域插槽:
<!-- 父組件 -->
<template>
<UserList>
<template #item="{ user }">
<p>{{ user.name }} - {{ user.age }}歲</p>
</template>
</UserList>
</template>
<!-- UserList組件 -->
<template>
<ul>
<li v-for="user in users" :key="user.id">
<slot name="item" :user="user"></slot>
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const users = ref([
{ id: 1, name: '張三', age: 20 },
{ id: 2, name: '李四', age: 22 }
]);
</script>總結(jié)
Vue3 的這些指令覆蓋了渲染、條件、循環(huán)、事件、屬性、雙向綁定、插槽等核心場景,是前端工程師高效開發(fā)的 “利器”。掌握它們的用法與場景,能讓你在 Vue 開發(fā)中事半功倍,寫出更簡潔、更易維護(hù)的代碼。
到此這篇關(guān)于Vue3中的常用指令的文章就介紹到這了,更多相關(guān)vue常用指令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue設(shè)計(jì)器form-create-designer配置表單默認(rèn)值示例詳解
這篇文章主要介紹了如何使用開源項(xiàng)目form-create-designer來靈活調(diào)整表單的默認(rèn)值,通過config.formOptions,您可以自定義表單的全局布局,文章提供了一個詳細(xì)的例子,展示了如何使用form-create-designer的配置選項(xiàng)來調(diào)整表單的布局和外觀,感興趣的朋友一起看看吧2024-11-11
uni-appx和uni-app的區(qū)別以及該如何選擇詳解
Uniapp?X是DCloud推出的下一代跨平臺應(yīng)用開發(fā)引擎,基于?TypeScript?和原生渲染技術(shù),性能顯著提升,接近原生應(yīng)用,這篇文章主要介紹了uni-appx和uni-app的區(qū)別以及該如何選擇的相關(guān)資料,需要的朋友可以參考下2025-09-09
vue-cli3.0+element-ui上傳組件el-upload的使用
這篇文章主要介紹了vue-cli3.0+element-ui上傳組件el-upload的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
vue踩坑記-在項(xiàng)目中安裝依賴模塊npm install報(bào)錯
這篇文章主要介紹了vue踩坑記-在項(xiàng)目中安裝依賴模塊npm install報(bào)錯,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

