App.vue
<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'
const data = ref([{
id: "1",
data: "aa"
},
{
id: "2",
data: "bb"
},
{
id: "3",
data: "cc"
},
{
id: "4",
data: "dd"
},
])
function add() {
data.value.splice(2, 0, {
id: "5",
data: "ff"
})
}
</script>
<template>
<div>
<button @click="add">add</button>
<div v-for="(item, index) in data" :key="index">
<Comp :index="index" :data="item"></Comp>
</div>
</div>
</template>
Comp.vue
<script setup>
import { watch } from 'vue'
const props = defineProps({
index: {
default: 0,
required: true
},
data: {
default: {
id: "",
data: ""
},
required: true
},
})
watch(() => props.index, (value) => {
console.log(value)
})
</script>
<template>
<div>
{{ props.data.id }}
</div>
</template>
I have one parent component and one child component. I use v-for
to reproduce Comp.vue
. I want to add new value between in data
array. And I want to see in watch
that index
changing. When I code like this, there is no any changing in index
. How can I get changed index
?
2
<div v-for="(item, index) in data" :key="item.id">
<Comp :index="index" :data="item"></Comp>
</div>
if I describe like this :key="item.id"
, vue understands that is unique and catch array changing for index. When I code like this, solved problem.