眾所周知,在Vue中是不推薦使用index
作為列表循環的key來綁定的,原因可見這篇文章 -> 在 Vue 中為什么不推薦用 index 做 key
那么,當我們遇到不得不避免使用index
作為key
,但同時后端傳來的數據中又沒有唯一標識字段的時候怎么辦呢?
辦法就是自己為數據添加唯一標識 —— uuid
(Universally Unique Identifier),當然這需要引入一個第三方庫 -> uuid
代碼如下(核心就是bindWithKey
函數):
<template>
<h3>{{ name }}</h3>
<div v-for="{ it, key } in list" :key="key">{{ it }} <input type="text" /></div>
<button @click="insert">插入一行</button>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import { v4 as uuidv4 } from 'uuid';
function bindWithKey<T>(arr: Array<T>): { it: T; key: string }[];
function bindWithKey<T>(arr: T): { it: T; key: string };
function bindWithKey(arr: Array<unknown> | string | number) {
return typeof arr === 'object' ? arr.map((v) => ({ it: v, key: uuidv4() })) : { it: arr, key: uuidv4() };
}
const list = reactive(bindWithKey(['haha', 'heihei', 'hehe']));
const insert = () => {
list.unshift(bindWithKey('hiahia'));
};
</script>
可以看出,這樣的做法會消耗一定的性能,但是如果情況所迫,比如數據量很大但偏偏需要頻繁逆序插入數據,或者出現了diff
算法導致的數據錯位不太能輕易解決的時候,那么可以考慮下本文的解決方案。
另外,雖然Vue建議采用唯一標識作為key
來綁定,但是一般情況下使用index
作為key
是不會有什么問題的,根據具體情況來決定吧