Vue中v-for的key值
在vue使用v-for的时候,如果没有后端返回的唯一id的话我就经常使用index来代替唯一id,以前没有发现什么问题,学过源码后知道了这可能导致vue组件不会更新,但是这么长时间,我还是没碰到这里出问题,于是就仍然这样写。
父组件:
<template>
<div class="dataPreview">
<div style="width: 100%; background-color: rgb(0 0 0 / 60%)">
<div class="indexContainer">
<div class="dataContainer">
<div class="preview">
<DataShowContent v-for="(item,index) in show" :key="index" :msg="item" />
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import DataShowContent from './DataShowContent.vue';
export default {
name: 'DataShow',
components: {
DataShowContent
},
data() {
return {
show: [
{
num: '0'
},
{
num: '0'
},
{
num: '0'
},
{
num: '0'
}
]
};
},
mounted() {
this.getMsg();
},
methods: {
async getMsg() {
this.show[2].num = 1;
}
}
};
</script>
子组件:
<template>
<div class="previewList">
<span class="icon">
<i :class="msg.ico" style="color: rgb(51 170 238);line-height: 70px"></i>
</span>
<h2 class="timer count-title" data-to="965" data-speed="1500">
{
{ num }}
</h2>
<p>{
{ message.name }}</p>
</div>
</template>
<script>
export default {
name: 'DataShowContent',
props: ['msg'],
mounted() {
this.getNum();
},
methods: {
getNum() {
console.log(this.msg.num);
}
}
};
</script>
在上面的代码中,我发现子组件中的getNum函数只输出了一次0,说明当父组件中的值更新后子组件中没有检测到,所以没有更新,这就是使用index做key值得问题了。于是我使用了nanoid库来改进。
nanoid
//npm i nanoid,安装nanoid
import {nanoid} from 'nanoid';//引入nanoid
nanoid();//nanoid的使用
父组件代码改进如下。
<template>
<div class="dataPreview">
<div style="width: 100%; background-color: rgb(0 0 0 / 60%)">
<div class="indexContainer">
<div class="dataContainer">
<div class="preview">
<DataShowContent v-for="item in show" :key="index.key" :msg="item" />
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {nanoid} from 'nanoid';
import DataShowContent from './DataShowContent.vue';
export default {
name: 'DataShow',
components: {
DataShowContent
},
data() {
return {
show: [
{
num: '0',
key: nanoid()
},
{
num: '0',
key: nanoid()
},
{
num: '0',
key: nanoid()
},
{
num: '0',
key: nanoid()
}
]
};
},
mounted() {
this.getMsg();
},
methods: {
async getMsg() {
this.show[2].key = nanoid();
this.show[2].num = 1;
}
}
};
</script>