跳至主要內容
版本:v8

Vue 效能

搭配 Ionic 元件使用 v-for

當搭配 Ionic 元件使用 v-for 時,我們建議使用 Vue 的 key 屬性。這能讓 Vue 透過僅更新元件內部的內容,而非完全重新建立元件,來有效率地重新渲染迴圈元素。

透過使用 key,您可以為每個迴圈元素提供穩定的識別碼,讓 Vue 可以追蹤迭代器中的插入和刪除。以下是如何使用 key 的範例:

<template>
<ion-page>
<ion-content>
<ion-item v-for="item of items" :key="item.id">
<ion-label>{{ item.value }}</ion-label>
</ion-item>
</ion-content>
</ion-page>
</template>

<script>
import { IonContent, IonItem, IonLabel, IonPage } from '@ionic/vue';
import { defineComponent } from 'vue';

export default defineComponent({
components: {
IonContent,
IonItem,
IonLabel,
IonPage
},
setup() {
const items = ref([
{ id: 0, value: 'Item 0' },
{ id: 1, value: 'Item 1' },
...
]);

return { items }
}
});
</script>

在此範例中,我們有一個名為 items 的物件陣列。每個物件都包含一個 value 和一個 id。使用 key 屬性,我們為每個物件傳遞 item.id。這個 id 用於為每個迴圈元素提供穩定的識別碼。

如需更多關於 Vue 如何使用 v-for 管理狀態的資訊,請參閱 https://v3.vuejs.org/guide/list.html#maintaining-state