Appearance
屬性綁定
命名規則
以 camelCase 命名的 props 在上層組件可以以 kebab-case(建議的方式) 或 camelCase 的命名方式傳遞 props。
html
<template>
<my-component :greeting-message></my-component>
</template><template>
<my-component :greeting-message></my-component>
</template>html
<template>
<my-component :greetingMessage></my-component>
</template><template>
<my-component :greetingMessage></my-component>
</template>基本語法
綁定 html 屬性:
html
<div v-bind:id="dynamicId"></div>
<a v-on:click="doSomething"> ... </a><div v-bind:id="dynamicId"></div>
<a v-on:click="doSomething"> ... </a>html
<div :id="dynamicId"></div>
<a @click="doSomething"> ... </a><div :id="dynamicId"></div>
<a @click="doSomething"> ... </a>物件綁定
下面兩者等價:
html
<template>
<div :id="obj.id" :class="obj.class"></div>
</template>
<script setup>
const obj = { id: 'container', class: 'wrapper' }
</script><template>
<div :id="obj.id" :class="obj.class"></div>
</template>
<script setup>
const obj = { id: 'container', class: 'wrapper' }
</script>html
<template>
<div v-bind="obj"></div>
</template>
<script setup>
const obj = { id: 'container', class: 'wrapper' }
</script><template>
<div v-bind="obj"></div>
</template>
<script setup>
const obj = { id: 'container', class: 'wrapper' }
</script>動態綁定
可依照不同情況將值綁定到不同屬性/事件:
vue
<!--attrName, eventName 可以是表達式-->
<a :[attrName]="url"> ... </a>
<a @[eventName]="doSomething"><!--attrName, eventName 可以是表達式-->
<a :[attrName]="url"> ... </a>
<a @[eventName]="doSomething">Boolean 屬性
例如要判斷 disable 狀態,可以使用 boolean attributes,使用 truthy value 條件判斷,但有例外:空字串視為 true。
html
<button :disabled="isButtonDisabled">Button</button><button :disabled="isButtonDisabled">Button</button>如果要判斷空字串為 false,最好的方法是先轉換成 true/false:
- !'' (
true) - !!'' (
false)
玩玩看
Summary
- 綁定的屬性或事件,命名方式為 kebab-case(建議) 或 camelCase。
- 事件綁定是
v-on:[事件名稱]語法糖@[事件名稱]。 - 屬性綁定是
v-bind:[屬性名稱]語法糖:[屬性名稱]。 - 綁定屬性
:onClick效果和@click相同,事件也是屬性的一種。 - 單純使用
v-bind是物件綁定,綁定物件下的所有屬性。