Vue 知识点 v-for 语法
v-for 指令 以 item in items 形式,来渲染一个列表,其中items是源迭代数据,而item是被迭代数据的元素。
- 在v-for值中,我们可以访问所有父作用域的property。多数情况下,v-for 还支持第二个参数,既当前项的索引。
- 也可以用of替代in作为分隔符,因为它更接近JavaScript迭代器的语法。
- items 可以是数组,也可以是对象。
- 注意:当v-for渲染元素列表时,默认使用就地更新策略,如果数据项的顺序被改变,vue不会移动DOM元素来匹配数据项,而是就地更新每个元素
- 尽可能在使用 v-for 时提供 key
Vue 将被侦听的数组的方法进行了包装,所以它们也会触发视图更新
- push
- pop
- sort
- reverse
- ......
代码片段
1 <view class="aaa" v-for="(item,index) List"
:key="index" @click="fun(item.Id)"> 2 <view class="box"> 3 <view class="img-box"> 4 <image class="img" :class="{'img-none':item.stock<1}" :src="item.goodsPicture" alt="商品" /> 5 <view v-if="item.stock<1" class="img-box-none">已售罄</view> 6 </view> 7 <view class="product-name">{{item.goodsName}}</view> 8 <view v-if="item['shopType']==='2'" class="display">仅展示</view> 9 <view v-else class="product-value">{{item.sellingPrice}}</view> 10 <!-- priceFiter --> 11 </view> 12 <view class="product-label" v-if="item.goodsLableList"> 13 <text class="label" v-if="index<3" v-for="(item2,index2) in item.goodsLableList" :key="index2">{{item2}}</text> 14 </view> 15 </view>
注: 由于JavaScript的限制,Vue不能检测数组和对象的变化。
有时,我们想要显示一个数组经过过滤或排序后的版本,而不实际变更或重置原始数据。在这种情况下,可以创建一个计算属性,来返回过滤或排序后的数组。
1 computed: { 2 3 testAfterList() { 4 let list = []; 5 for (var i = 0; i < this.testList.length; i++) { 6 let item = this.testList[i]; 7 if (item.show) { 8 list.push(item); 9 } 10 } 11 return list; 12 } 13 }
待续