Vue3列表移除元素后索引更新實(shí)現(xiàn)方法
方法1:使用 v-for 的 index 自動更新
Vue 會自動處理 v-for 中的索引,當(dāng)你移除一個元素后,剩余元素的索引會自動更新:
<template>
<div>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }} (Index: {{ index }})
<button @click="removeItem(index)">Remove</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
function removeItem(index) {
items.value.splice(index, 1);
}
</script>方法2:使用唯一標(biāo)識而非索引作為 key
最佳實(shí)踐是使用唯一標(biāo)識作為 key,而不是索引:
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
<button @click="removeItem(item.id)">Remove</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
function removeItem(id) {
items.value = items.value.filter(item => item.id !== id);
}
</script>方法3:計算屬性維護(hù)索引
如果需要存儲索引而不想它隨列表變化而改變,可以使用計算屬性:
<template>
<div>
<ul>
<li v-for="(item, index) in itemsWithStableIndex" :key="item.id">
{{ item.name }} (Original Index: {{ item.originalIndex }})
<button @click="removeItem(index)">Remove</button>
</li>
</ul>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const items = ref([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
]);
const itemsWithStableIndex = computed(() => {
return items.value.map((item, index) => ({
...item,
originalIndex: index
}));
});
function removeItem(index) {
items.value.splice(index, 1);
}
</script>注意事項
避免直接使用索引作為 key,這可能導(dǎo)致渲染問題
Vue 會自動更新 v-for 中的索引,所以通常不需要手動處理
如果需要在移除后執(zhí)行其他操作,可以使用 watch 或 watchEffect 監(jiān)聽列表變化
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue+element+cookie記住密碼功能的簡單實(shí)現(xiàn)方法
這篇文章主要給大家介紹了Vue+element+cookie記住密碼功能的簡單實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
vue單向數(shù)據(jù)綁定和雙向數(shù)據(jù)綁定方式
這篇文章主要介紹了vue單向數(shù)據(jù)綁定和雙向數(shù)據(jù)綁定方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
在IDEA中Debug調(diào)試VUE項目的詳細(xì)步驟
idea竟然有一個神功能很多朋友都不是特別清楚,下面小編給大家?guī)砹嗽贗DEA中Debug調(diào)試VUE項目的詳細(xì)步驟,感興趣的朋友一起看看吧2021-10-10
maptalks+three.js+vue webpack實(shí)現(xiàn)二維地圖上貼三維模型操作
這篇文章主要介紹了maptalks+three.js+vue webpack實(shí)現(xiàn)二維地圖上貼三維模型操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

