我把v-if和v-for同时用在了van-swipe-item 元素身上结果报错了!!!
代码如下:
<van-swipe-item v-if="state.content.photoGallery" v-for="(photo, index) in state.content.photoGallery" :key="index"><img :src="photo.imageUrl" alt="image" @click="look2(index)"></van-swipe-item>
报错如下:
8:41 error This 'v-if' should be moved to the wrapper element vue/no-use-v-if-with-v-for
怎么办?后来我就去查百度,百度说 v-if 和 v-for 同时使用的话,v-for的权力比v-if高,所以Vue会先执行v-for然后再去判断v-if。
这样会出现什么问题呢?资源的浪费,先v-for渲染很多元素,然后在一个一个的去判断,Vue会很累的,还会报错所以Vue官方不推荐 v-if 和 v-for同时用在一个元素身上。(注意)
解决办法:
<template v-if="state.content.photoGallery">
<van-swipe-item v-for="(photo, index) in state.content.photoGallery" :key="index"><img :src="photo.imageUrl" alt="image" @click="look2(index)"></van-swipe-item>
</template>
给van-swipe-item外面包裹一个template标签,在template标签里面写判断,这样 v-if 和 v-for 就不会冲突了,而且使用template标签有一个好处,是template标签没有DOM结构。