Vue项目画廊页面切换后图片随机加载失败问题求助
Vue 画廊页面图片加载异常问题
首次进入画廊页面时图片加载正常,但切换至其他页面(如首页)再返回画廊页面时,图片完全不加载,容器为空,页面切换会导致画廊图片随机加载失败。
加载失败时的页面状态:
获取画廊数据的代码
import { reactive} from 'vue'; export default { transition:'fade', layout: 'layout_port', data(){ return{ filter:'original', indexGal: null, sortmenu:['original','fanart','concepts','graphic design'], gallery: reactive (['static images here']), } }, computed:{ fetchedGallery() { if (this.filter) { return this.gallery.filter(i => i.cat === this.filter) } return this.gallery } }, }
图片展示的Vue模板代码
#portfolio v-main v-container(fluid).ma-0.pa-0 v-layout(justify-center) v-flex(xs12 text-xs-center) v-card(flat color='transparent') ul li(v-for='(category,index) in sortmenu' :key='index' :item='category' @click='filter = category' :class="{ active: category == filter }") {{ category }} v-layout() v-flex(xs12 sm6 offset-sm3) v-card(flat color='white').gallery v-container(grid-list-sm fluid) v-layout(row wrap) //keep-alive v-flex(v-for='(image,index) in fetchedGallery', :key='index' :item='image',xs6 sm4 d-flex) v-card.d-flex(flat tile color='transparent').galim.pa-4 v-img.grey.lighten-2(:src='image.url', :lazy-src='image.url', aspect-ratio='1' @click='indexGal = index') br no-ssr LightGallery(:images='fetchedGallery' :index='indexGal' :disable-scroll='true' @close='indexGal = null' interfaceColor='rgba(255,253,238)' background='rgba(0,0,0,0.95)')
问题原因及解决方案
组件销毁重建导致数据未重新加载
组件切换时会被销毁,返回时重新初始化,若没有重新获取数据,gallery会停留在初始的['static images here']状态。需在组件挂载时加载数据:mounted() { this.loadGalleryData(); }, methods: { async loadGalleryData() { // 替换为实际数据请求逻辑,比如接口获取或静态数据赋值 // const res = await axios.get('/api/gallery'); // this.gallery = reactive(res.data); this.gallery = reactive([ // 示例图片数据:{ url: 'xxx.jpg', cat: 'original' } ]); } }用
keep-alive缓存组件状态
若不想每次返回都重新加载数据,可通过keep-alive保留组件实例:
在路由出口处配置:<keep-alive> <router-view v-if="$route.meta.keepAlive" /> </keep-alive> <router-view v-if="!$route.meta.keepAlive" />给画廊页面路由添加元信息:
{ path: '/portfolio', component: Portfolio, meta: { keepAlive: true } }修复
v-for的key值
当前用index作为key易导致DOM复用异常,建议改用图片的唯一标识(如image.id):v-flex(v-for='(image,index) in fetchedGallery', :key='image.id' :item='image',xs6 sm4 d-flex)重新初始化LightGallery
组件重建后LightGallery可能未更新,可监听数据变化手动触发刷新:watch: { fetchedGallery(newVal) { if (newVal.length > 0) { this.$nextTick(() => { this.$refs.lightGallery.refresh(); }); } } }给LightGallery添加
ref:LightGallery(ref='lightGallery' :images='fetchedGallery' ...)
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

