好的,我們來學習 v-bind
指令。這個指令是理解 Vue 數據驅動思想的基石。
核心功能:v-bind
的作用是將一個或多個 HTML 元素的 attribute (屬性) 或一個組件的 prop (屬性) 動態地綁定到 Vue 實例的數據上。
簡單來說,它在你的數據和 HTML 元素的屬性之間建立了一座橋梁。當你的數據變化時,HTML 元素的屬性也會自動更新。
v-bind 有一個非常常用的簡寫形式,就是一個冒號 (:
)。在實際開發中,你幾乎總會使用簡寫形式。
例如,v-bind:href
和 :href
是完全等效的。
v-bind
指令(CDN 方式)
下面是一個完整的 HTML 文件,通過多個示例展示了 v-bind
的核心用法。
示例代碼
你可以將此代碼保存為 .html
文件,并在瀏覽器中打開。嘗試在瀏覽器的開發者工具中修改 app.vueData
的值,觀察頁面元素的屬性如何實時變化。
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Vue 3 v-bind 示例 (CDN)</title><style>body { font-family: system-ui, sans-serif; padding: 20px; color: #333; }#app { max-width: 800px; margin: 0 auto; padding: 25px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }.demo-item { padding: 15px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; }.demo-item h3 { margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px; }.text-danger { color: red; }.is-active { background-color: #42b883; color: white; font-weight: bold; }.text-large { font-size: 20px; }.static-class { border: 2px solid blue; }button { padding: 8px 15px; border-radius: 4px; border: 1px solid #ccc; cursor: pointer; }button:disabled { cursor: not-allowed; opacity: 0.5; }a { color: #42b883; text-decoration: none; }a:hover { text-decoration: underline; }</style>
</head>
<body><div id="app"><h1>v-bind (簡寫 :) 使用示例</h1><div class="demo-item"><h3>1. 綁定標準 Attribute</h3><p :id="elementId">這個 p 標簽的 ID 是動態綁定的。</p><a :href="linkUrl">這是一個動態鏈接,指向 Vue 官網</a><br><img :src="imageUrl" alt="Vue Logo" width="50"></div><div class="demo-item"><h3>2. 綁定 Class (最常用)</h3><p class="static-class" :class="{ 'is-active': isActive, 'text-danger': hasError }">對象語法綁定 Class。</p><p :class="[activeClass, largeTextClass]">數組語法綁定 Class。</p><p :class="['static-class', { 'is-active': isActive }]">混合語法綁定 Class。</p></div><div class="demo-item"><h3>3. 綁定 Style</h3><p :style="{ color: activeColor, fontSize: fontSize + 'px' }">對象語法綁定 Style。</p><p :style="[baseStyles, overrideStyles]">數組語法綁定 Style。</p></div><div class="demo-item"><h3>4. 綁定布爾類型 Attribute</h3><button :disabled="isButtonDisabled">這是一個按鈕</button><p>當 `isButtonDisabled` 為 `true` 時,按鈕被禁用。為 `false` 或 `null` 或 `undefined` 時,`disabled` 屬性會被移除。</p></div><div class="demo-item"><h3>5. 一次性綁定多個 Attribute</h3><div v-bind="objectOfAttrs">這個 div 通過一個對象綁定了 id 和 class。</div></div></div><script src="https://unpkg.com/vue@3/dist/vue.global.js"></script><script>const { createApp, ref, reactive, computed } = Vue;const app = createApp({setup() {// 1. 用于綁定標準 Attribute 的數據const elementId = ref('my-unique-id');const linkUrl = ref('https://vuejs.org');const imageUrl = ref('https://vuejs.org/images/logo.png');// 2. 用于綁定 Class 的數據const isActive = ref(true);const hasError = ref(false);const activeClass = ref('is-active');const largeTextClass = ref('text-large');// 3. 用于綁定 Style 的數據const activeColor = ref('darkblue');const fontSize = ref(18);const baseStyles = reactive({fontWeight: 'bold'});const overrideStyles = reactive({color: 'green',borderLeft: '5px solid green'});// 4. 用于綁定布爾 Attribute 的數據const isButtonDisabled = ref(true);// 5. 用于一次性綁定多個值的對象const objectOfAttrs = reactive({id: 'multi-bind-div',class: 'is-active text-large'});// 方便在控制臺操作window.app = {vueData: {elementId, linkUrl, isActive, hasError, activeColor, fontSize, isButtonDisabled, objectOfAttrs}};// 3 秒后改變一些值,來觀察動態效果setTimeout(() => {isActive.value = false;hasError.value = true;activeColor.value = 'purple';fontSize.value = 22;isButtonDisabled.value = false;objectOfAttrs.class = 'text-danger'; // 改變對象的屬性}, 3000);return {elementId,linkUrl,imageUrl,isActive,hasError,activeClass,largeTextClass,activeColor,fontSize,baseStyles,overrideStyles,isButtonDisabled,objectOfAttrs};}});app.mount('#app');
</script></body>
</html>
主要用法匯總
1. 綁定普通 HTML Attribute
這是最基礎的用法。你可以綁定任何標準的 HTML 屬性。
- 語法:
:attributeName="dataProperty"
- 示例:
<a :href="userProfileUrl">個人資料</a>
這里<a>
標簽的href
屬性會隨著userProfileUrl
數據的變化而更新。
2. 綁定 class
這是 v-bind
最強大和常用的功能之一。你可以非常靈活地控制元素的類名。
- 對象語法:
:class="{ 'active-class': isActive, 'error-class': hasError }"
當數據isActive
為真值時,元素會擁有active-class
類名,hasError
同理。 - 數組語法:
:class="[classA, classB]"
元素會同時擁有classA
和classB
變量所代表的類名。 - 混合使用: 數組和對象語法可以結合使用,提供了極高的靈活性。
3. 綁定 style
(內聯樣式)
你可以動態地控制元素的內聯樣式。
- 對象語法:
:style="{ color: activeColor, fontSize: size + 'px' }"
CSS 屬性名推薦使用駝峰式 (fontSize
),但也可以用帶引號的短橫線分隔式 ('font-size'
)。 - 數組語法:
:style="[baseStyles, overridingStyles]"
可以將多個樣式對象合并應用到一個元素上,后面的對象會覆蓋前面對象的同名屬性。
4. 綁定布爾類型 Attribute
對于像 disabled
, checked
, selected
這樣的布爾屬性,Vue 有特殊的處理邏輯。
- 語法:
:disabled="isButtonDisabled"
- 規則: 當
isButtonDisabled
的值為真值 (true
,''
, 對象等) 時,disabled
屬性會被添加到元素上。當其值為假值 (false
,null
,undefined
) 時,disabled
屬性會被從元素上移除。
5. 綁定一個包含多個 Attribute 的對象
如果你需要為一個元素動態綁定多個屬性,可以傳遞一個對象。
- 語法:
v-bind="objectOfAttrs"
- 示例: 如果
objectOfAttrs
是{ id: 'my-el', class: 'active' }
,那么它等價于<div id="my-el" class="active">
。
v-bind
是 Vue 中數據驅動視圖的核心,熟練掌握它的各種用法對于編寫動態和響應式的界面至關重要。