请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

v- for 中的key为什么不建议使用index

当循环一个数组例如[{name:'1'},{name:'2'},{name:'3'}]时,删除第二项

<template>
  <hello-world
    v-for="(item, index) in arr"
    :key="index"
    :count="item.count"
    :name="item.name"
    @del="del(index)"
  ></hello-world>
</template>

<script setup>
import { reactive } from "vue";
import HelloWorld from "./components/HelloWorld.vue";

const arr = reactive([
  { name: "第一个", count: 1 },
  { name: "第二个", count: 2 },
  { name: "第三个", count: 3 },
]);

const del = (index) => {
  console.log("删除", index + 1);
  arr.splice(index, 1);
};
</script>
<template>
  <div>
    <span>{{ name }}</span>
    <span>count: {{ innerCount }}</span>
    <a @click="del">删除</a>
  </div>
</template>

<script setup>
import { defineEmit, defineProps, reactive } from "vue";

const props = defineProps({
  name: "",
  count: "",
});

const emit = defineEmit(["del"]);
const del = () => {
  emit("del");
};

const innerCount = props.count;
</script>


https://img1.sycdn.imooc.com//szimg/64d99962094d7a5502310093.jpghttps://img1.sycdn.imooc.com//szimg/64d9993c09e12eda02650104.jpg

正在回答 回答被采纳积分+3

1回答

Sunday 2023-08-14 21:15:56

你好

key的话期望使用《唯一且不会发生变化的数据》,而 index 是可能发生变化的(比如 unshift)

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号