v-for使用注意点
v-for属性不能放在绑定的根元素上
绑定在根元素上会报错:Cannot use v-for on stateful component root element because it renders multiple elements.
同时根元素也不能是<template>
// 创建组件
Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})
// 创建Vue实例,绑定id=“blog-post-demo”
new Vue({
el: '#blog-post-demo',
data: {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
]
}
})
// 正确代码
<div id="blog-post-demo">
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title">
</blog-post>
</div>
// 错误代码,会报错:Cannot use v-for on stateful component root element because it renders multiple elements.
<blog-post
id="blog-post-demo"
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title">
</blog-post>
v-bind:key
https://blog.csdn.net/luwenze/article/details/84564934
<li v-for="(item, key, index) in items" class="animate" v-bind:key="item.id">{{item.id}}</li>
1.使用给数组对象绑定的id属性
// items data
items: [ { id: 2, }, { id: 1, }, { id: 3, }, { id: 4, }, ]
2.使用v-for提供的index参数
3.使用v-for提供的key参数
结论:
1.使用v-for渲染元素时,使用元素自身的id属性去绑定key值有利于单个元素的重新渲染
2.若采用其他如v-for提供的index, key等值,在改变渲染出来的DOM结构时,会触发所有元素的重新渲染,当数据过大时,可能会造成性能负担。
总结:
当我们在使用v-for进行渲染时,尽可能使用渲染元素自身属性的id给渲染的元素绑定一个key值,这样在当前渲染元素的DOM结构发生变化时,能够单独响应该元素而不触发所有元素的渲染。