首先,vue使用虚拟dom进行渲染时,为了提高效率和性能会选择性的复用一些元素,加上key值之后,可以让虚拟dom进行复用时,进行区分,复用的元素因为key值的不同不会进行重复使用,避免bug。
比如:使用v-for循环进行渲染时,翻页过程中li会被复用,里面的input也会被复用里面的value值翻页的时候还会重复存在。
<template>
<div>
<ul>
<li v-for=" item,index in arr.slice(n,n+4)" :key="item">{{ item }}
<input type="text">
</li>
</ul>
<button @click="top">上一页</button><button @click="bop">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
arr: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',],
n: 0,
}
},
methods:{
top(){
this.n-=4
},
bop(){
this.n+=4
}
}
}
</script>