🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 列表渲染指令v-for 我们用 v-for 指令根据一组数组的选项列表进行渲染。v-for 指令需要使用 item in items 形式的特殊语法,items 是源数据数组并且 item 是数组元素迭代的别名。v-for 还支持一个可选的第二个参数index为当前项的索引。 示例: ``` <!-- 在这种嵌套循环的时候, index 和 itemIndex 这种索引是必须指定,且别名不能相同,正确的写法如下 --> <template> <scroll-view v-for="(card, index) in list" :key="index"> <view v-for="(item, itemIndex) in card" :key="itemIndex"> {{item.value}} </view> </scroll-view> </template> ``` 为了能跟踪每个节点的身份,从而重用和重新排序现有元素,你需要为每项提供一个唯一 key 属性。理想的 key 值是每项都有的且唯一的 id,它的工作方式类似于一个属性,所以你需要用 v-bind 来绑定动态值。 > uni-app中嵌套列表渲染,必须指定不同的索引!需要填写:key="xx",或者v-bind:key=”xx”。 以下的示例演示了如何结合v-show指令和v-for指令条件输出,并使用Flex布局生成表格输出。 > 本例演示了Flex布局的垂直居中和水平居中,表格的每一列占屏幕宽度的1/3。 * [ ] pages/lab/gramma/vfor.vue ``` <!-- pages/lab/gramma/vfor.vue --> <template> <view style="flex-direction: column; flex: 1; justify-content: center;"> <view> <view class="table-item">索引</view> <view class="table-item">姓名</view> <view class="table-item">年龄</view> </view> <block v-for="(item, index) in students" :key="index"> <view v-if="item.age >=20"> <view class="table-item">{{index}}</view> <view class="table-item">{{item.name}}</view> <view class="table-item">{{item.age}}</view> </view> </block> </view> </template> <script> export default { data() { return { students: [{ name: "张三", age: 18 }, { name: "李四", age: 20 }, { name: "王五", age: 21 } ] } } } </script> <style> view { display: flex; flex-direction: row; } .table-item { display: flex; flex: 1; justify-content: center; align-items: center; } </style> ``` ![](https://box.kancloud.cn/062e94705309cd1273dcf2b4acfa2d7a_914x779.png) ### [key](https://uniapp.dcloud.io/use?id=key) 如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如`<input>`中的输入内容,`<switch>`的选中状态),需要使用`:key`来指定列表中项目的唯一的标识符。 `:key`的值以两种形式提供 * 使用`v-for`循环`array`中`item`的某个`property`,该`property`的值需要是列表中唯一的字符串或数字,且不能动态改变。 * 使用`v-for`循环中`item`本身,这时需要`item`本身是一个唯一的字符串或者数字 当数据改变触发渲染层重新渲染的时候,会校正带有`key`的组件,框架会确保他们被重新排序,而不是重新创建,以确保使组件保持自身的状态,并且提高列表渲染时的效率。 **如不提供`:key`,会报一个`warning`, 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。** **示例:** ~~~ <template> <view> <!-- array 中 item 的某个 property --> <view v-for="(item,index) in objectArray" :key="item.id"> {{index +':'+ item.name}} </view> <!-- item 本身是一个唯一的字符串或者数字时,可以使用 item 本身 --> <view v-for="(item,index) in stringArray" :key="item"> {{index +':'+ item}} </view> </view> </template> <script> export default { data () { return { objectArray:[{ id:0, name:'li ming' },{ id:1, name:'wang peng' }], stringArray:['a','b','c'] } } } </script> ~~~