key值問題
報錯信息
vue.runtime.esm.js?2b0e:619 [Vue warn]: Duplicate keys detected: '0'. This may cause an update error.
代碼
<a-select v-model="formVals.status" style="width: 150px">
<a-select-option value="" key="0">All</a-select-option>
<a-select-option
:value="item.status"
v-for="(item, index) in statusList"
:key="`${(index + 1)}`"
>
{{ item.statusText }}
</a-select-option>
</a-select>
問題分析
在開發過程中,使用v-for 命令出現了報錯,一開始以爲是爲key屬性賦值${(index + 1)}
的寫法有問題導致了重複,後來發現不是,想起曾經遇到過類似的問題,產生該報錯的原因不是因爲當前for循環中出現了重複的值,而是因爲在頁面中使用了多個v-for ,導致的在多個v-for中的項目出現key值重複,例如:
<a-select v-model="status" style="width: 150px">
<a-select-option value="" key="0">All</a-select-option>
<a-select-option
:value="item.status"
v-for="(item, index) in statusList"
:key="`${(index + 1)}`"
>
{{ item.statusText }}
</a-select-option>
</a-select>
<a-select v-model="name" style="width: 150px">
<a-select-option value="" key="0">All</a-select-option>
<a-select-option
:value="item.userId"
v-for="(item, index) in userList"
:key="`${(index + 1)}`"
>
{{ item.name}}
</a-select-option>
</a-select>
我們在爲:key
賦值的時候可以採用多種方式:
- :key="
${(index + 1)}
" - :key=“index + 1”
然而當我修改了v-for的key後仍然存在該問題,我無奈了,究竟是什麼境況導致的!!!!!根本沒有重複的key啦!!!
重點來了!!!!!
我不厭其煩的細細查看,然後,最後發現居然是v-for 循環中的 value是一樣的!!!!!
模擬的數據重複了,這個太討厭了!!!!!
好吧,但是報錯的時候居然提示的是key值重複!!!!!