Appearance
指示詞 (Directive)
只介紹比較常用的
Conditional Rendering
v-if
:條件成立才渲染。v-show
:一律渲染,條件成立才顯示,不成立會加上style="display: none;"
。
v-else/v-else-if
html
<div v-if="type === 'A'"> A </div>
<div v-else-if="type === 'B'"> B </div>
<div v-else-if="type === 'C'"> C </div>
<div v-else> Not A/B/C </div>
<div v-if="type === 'A'"> A </div>
<div v-else-if="type === 'B'"> B </div>
<div v-else-if="type === 'C'"> C </div>
<div v-else> Not A/B/C </div>
v-for
用來做清單渲染
- key 屬性不能重複。
- 以 key 判斷清單改變後,是否重新渲染某列表的依據(增進效能)。
- 變動性的資料應該用 id 作為 key。
- 不變的資料可以用 index 作為 key。
html
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
<div v-for="item in items" :key="item.id">
{{ item.text }}
</div>
v-bind/v-on
v-bind
: 屬性綁定,縮寫為:
(見元件屬性綁定)。v-on
: 事件綁定,縮寫為@
。- 常用修飾詞:
.stop
- 自動呼叫 event.stopPropagation(),中止事件傳遞。.prevent
- 自動呼叫 event.preventDefault(),取消事件預設動作。
html
<button v-on:click.stop="onClick"></button>
<button v-on:click.stop="onClick"></button>
v-model
雙向綁定語法糖
vue
<template>
<!-- 兩者等價 -->
<MyComponent :modelValue="count" @update:modelValue="count=$event" />
<MyComponent v-model="count" />
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
<template>
<!-- 兩者等價 -->
<MyComponent :modelValue="count" @update:modelValue="count=$event" />
<MyComponent v-model="count" />
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
多值雙向綁定 試試看
v-slot
用於指定具名插槽、從作用域插槽獲取屬性。先大致了解內容和結構,後面有專門章節。
html
<!-- 具名插槽 -->
<BaseLayout>
<template v-slot:header>
頁首內容
</template>
<template v-slot:default>
預設插槽內容
</template>
<template v-slot:footer>
頁尾內容
</template>
</BaseLayout>
<!-- 具名插槽接收屬性 -->
<InfiniteScroll>
<template v-slot:item="slotProps">
<div class="item">
{{ slotProps.item.text }}
</div>
</template>
</InfiniteScroll>
<!-- 預設插槽接收屬性,並使用解構賦值 -->
<Mouse v-slot="{ x, y }">
滑鼠位置: {{ x }}, {{ y }}
</Mouse>
<!-- 具名插槽 -->
<BaseLayout>
<template v-slot:header>
頁首內容
</template>
<template v-slot:default>
預設插槽內容
</template>
<template v-slot:footer>
頁尾內容
</template>
</BaseLayout>
<!-- 具名插槽接收屬性 -->
<InfiniteScroll>
<template v-slot:item="slotProps">
<div class="item">
{{ slotProps.item.text }}
</div>
</template>
</InfiniteScroll>
<!-- 預設插槽接收屬性,並使用解構賦值 -->
<Mouse v-slot="{ x, y }">
滑鼠位置: {{ x }}, {{ y }}
</Mouse>
Summary
v-if
:條件成立才渲染,後面可接v-else
/v-else-if
。v-show
:一律渲染,條件成立才顯示(不成立會加上style="display: none;"
)。v-for
:清單渲染- 變動性的資料應該用 id 作為 key
- 不變的資料可以用 index 作為 key
- 事件綁定 (
v-on
/@
) 常用修飾詞:.prevent
、.stop
v-model
:雙向綁定語法糖。- 不指定綁定值的話(
v-model="xxx"
)預設綁定modelValue
這個 props。 - 指定其他
props
綁定:v-model:somevalue="xxx"
。 - 可綁定多個值。
- 不指定綁定值的話(
v-slot
嵌入插槽,先大致了解內容和結構,後面有專門章節。