如何在Vue-turnjs中动态添加API拉取的页面并解决无page-wrapper类问题
问题原因
你用到的fw-turn(封装turn.js的Vue组件)仅会在首次组件挂载时扫描所有子页面元素,自动添加.page、.page-wrapper类并注册到翻页逻辑中。后续你通过push往数组新增页面,Vue渲染出新的DOM元素后,turn.js不会自动识别处理这些新增元素,因此无法参与翻页。
解决方案
方案1:简单快捷(适合页面总量不大的场景)
给fw-turn组件绑定key属性为页面列表的长度,每次新增页面后key变化会触发组件重新初始化,turn.js会自动扫描所有页面完成注册:
<!-- ReadItem.vue 中修改fw-turn标签 --> <fw-turn ref="turnRef" class="magazine" :options="options" :key="pages.length" >
该方案缺点是重新初始化时会有轻微的视觉闪烁,优点是无需修改额外逻辑。
方案2:性能最优(无闪烁,适合大页数场景)
监听页面数组变化,手动调用turn.js原生的addPage方法添加新页面,不需要重新渲染已有页面:
// ReadItem.vue 中新增watch逻辑 watch: { 'contentBook.rows': { deep: true, handler(newRows) { this.$nextTick(() => { // 获取turn.js实例,根据你fw-turn的封装调整取值方式,常见的有以下几种: const turnInstance = this.$refs.turnRef.$turn || this.$refs.turnRef.instance || this.$refs.turnRef.$el.turn('instance') const existPageCount = turnInstance.turn('pages') // 只处理新增的页面 const addPages = newRows.slice(existPageCount) addPages.forEach((pageItem, idx) => { // 构造和你模板结构一致的页面DOM const pageDom = document.createElement('div') pageDom.className = 'relative' let attachHtml = '' if (pageItem.attachments.length) { attachHtml = `<div class="absolute top-0 left-0 w-full h-full">` pageItem.attachments.forEach(attach => { const type = this.checkType(attach.type) attachHtml += `<img src="/images/book/${type}.svg" class="absolute cursor-pointer rounded-2xl ${type}" style="left: ${attach.verticalPosition}%; top: ${attach.horizontalPosition}%" alt="" >` }) attachHtml += `</div>` } pageDom.innerHTML = ` <img class="w-full h-full" src="${pageItem.image}" alt=""> ${attachHtml} ` // 插入到turn.js实例最后 turnInstance.turn('addPage', pageDom, existPageCount + idx + 1) }) }) } } }
额外优化建议
你当前在turning事件中判断page%12===0触发拉取,建议新增已拉取页码的缓存判断,避免重复请求同一分页的内容:
// ReadItem.vue data中新增字段 data() { return { fetchedPages: [1], // 初始默认已经拉了第一页 // 其余原有字段不变 } } // 修改turning事件逻辑 turning: (_, page) => { this.first = false; this.last = false; const fetchPage = Math.floor(page / 12) + 1; if (page % 12 === 0 && !this.fetchedPages.includes(fetchPage)) { this.fetchedPages.push(fetchPage) this.$emit('onAddPage', fetchPage); } this.$emit('onChangeCurrentPage', page); }
内容的提问来源于stack exchange,提问作者Stone0409
相关产品推荐
相关产品推荐

