鍍金池/ 問答/HTML/ v-for="(item, index) in list"循

v-for="(item, index) in list"循環(huán)子組件,刪除第n個組件后,其后的組件會更新,無法保持狀態(tài)

更新嘗試如下:
父組件:

<template>
  <div>
    <div style="height: 45px;"></div>
    <div v-for="(item, index) in list" :key="item.key">
      <child :key="item.key" :value="item" :key="index"></child>
      <div @click="deleteOne(index)">delete</div>
      <div style="height: 40px"></div>
    </div>
  </div>
</template>
<script>
  import child from './child.vue'
  export default {
    components: {
      child
    },
    data () {
      return {
        list: [
          {val: 111, key: 1},
          {val: 222, key: 2},
          {val: 333, key: 3},
          {val: 444, key: 4},
          {val: 555, key: 5}]
      }
    },
    methods: {
      deleteOne (index) {
        this.list.splice(index, 1)
      }
    }
  }
</script>
<style scoped>
</style>

子組件:
<template>
<div>

{{value}} + {{random}}

</div>
</template>
<script>

export default {
  props: ['value'],
  data () {
    return {
      random: Math.random()
    }
  }
}

</script>
<style scoped>
</style>
測試結(jié)果如下:
初始為:
圖片描述

刪除3后:
圖片描述

發(fā)現(xiàn)刪除3后 組件1 2 沒有更新,但是 4 5 更新了。
補充問題:有沒有辦法保持4 5 的狀態(tài)呢?
—————————————————————————————————————————————————
原問題:
父組件通過remove函數(shù)list.splice(n, 1),刪除了一個子組件,input被刪除的是第n個,但子組件不是第n個而是最后一個,請問怎么做才能實現(xiàn)傳刪除第n個子組件呢?

父組件:

<div v-for="(item, index) in list">
 <input type="text" v-model="item.data">
 <child :options="item.option"></child>
 <div @click="remove(index)">delete</div>
</div>
data () {
 return {
  list: [
   {data:'123', option: {...}},
   {data:'456', option: {...}},
   {data:'789', option: {...}}
  ]
 }
}
methods: {
 remove(n) {
   list.splice(n, 1)
 }
}

子組件:

<div>...</div>

回答
編輯回答
擱淺

為每個子組件加上key試一下

2017年8月18日 17:28
編輯回答
局外人

為每個組件上加獨一無二的key,注意此處如果以list的每項的index作為key值可能會出現(xiàn)組件銷毀的錯誤。推薦 lodash 的 uniqueId()。

2018年6月30日 09:48
編輯回答
祈歡

你目前放上的代碼沒問題,list是簡寫了吧 this.list
list.splice(2,1)的時候是刪除下標2整項都刪除,不會出現(xiàn)2這一項里子對象有的刪除錯誤

2018年5月20日 01:59
編輯回答
愚念
v-if = "key == n"
2017年5月14日 10:39