Commit 19a98200 by liimin

refactor(components): 优化轮播组件自动播放逻辑和内存管理

refactor(pages): 重构详情页数据结构并优化性能

fix(components): 修复轮播组件销毁时未清理定时器的问题
1 parent 4747dbb0
......@@ -77,6 +77,16 @@ export default {
this.getDatalist()
if (this.autoplay) this.autoPlayFunction()
},
beforeDestroy() {
if (this.autoPlayTimer) {
clearTimeout(this.autoPlayTimer)
this.autoPlayTimer = null
}
if (this.endTimer) {
clearTimeout(this.endTimer)
this.endTimer = null
}
},
methods: {
getDatalist() {
this.datalist = this.moduleList
......@@ -195,6 +205,13 @@ export default {
})
}
},
restartAutoPlay() {
if (this.autoPlayTimer) clearTimeout(this.autoPlayTimer)
this.autoPlayTimer = setTimeout(() => {
this.playStatus = true
this.autoPlayFunction()
}, this.interval)
},
starts(e) {
this.ismove = e.touches[0].pageX
this.playStatus = false
......@@ -212,16 +229,16 @@ export default {
if (nums > 30) this.updateCarouselPositions('left')
if (nums < -30) this.updateCarouselPositions('right')
this.endTimer = setTimeout(() => {
this.playStatus = true
this.autoPlayFunction()
}, this.interval)
this.restartAutoPlay()
},
handleClick(item) {
if (item.class !== 'block-center') {
// 点击两侧卡片也可以切换
if (item.class === 'block-right') this.updateCarouselPositions('left')
if (item.class === 'block-left') this.updateCarouselPositions('right')
// 重置自动轮播计时器
this.restartAutoPlay()
return
}
const data = this.moduleList[item.isIndex]
......
......@@ -3,36 +3,36 @@
* @Author: huyue
* @Date: 2024-04-08 11:30:30
* @LastEditors: limin
* @LastEditTime: 2025-12-29 11:40:42
* @LastEditTime: 2025-12-31 14:04:11
-->
<template>
<view class="detail-box" :key="dateilKey">
<view class="nav-bar" :style="{ 'z-index': backZindex }">
<view class="detail-box" :key="ui.dateilKey">
<view class="nav-bar" :style="{ 'z-index': ui.backZindex }">
<view class="back" @click="back">
<uni-icons type="left" :size="20" color="#000"></uni-icons>
</view>
</view>
<template v-for="(item, index) in moduleList">
<view :class="['view', getViewClass(item)]" :style="{ 'animation-duration': swipeConfig.animDuration + 'ms' }" :key="index" @touchstart.stop="touchStart"
<template v-for="(item, index) in list.moduleList">
<view :class="['view', getViewClass(item, index)]" :style="{ 'animation-duration': config.swipeConfig.animDuration + 'ms' }" :key="index" @touchstart.stop="touchStart"
@touchend.stop="touchEnd">
<!-- 优化:仅渲染当前页、上一页、下一页,减少DOM节点 -->
<component
v-if="shouldRender(item)"
v-if="shouldRender(index)"
@full="handleFull" :detail="item" :is="item.componentName"
:views="item.receptionSourceDetailList || []" :penSwitch="penSwitch" :show="id == item.id"
:ref="'media' + item.id" :title="item.materialName || ''" :madiaId="item.id" @scale="scale"
:ulList="item.ulList" :screenList="item.screenList" @onProductModel="productModelStatus = $event"
:ulList="item.ulList" :screenList="item.screenList" @onProductModel="ui.productModelStatus = $event"
:isPreview="isPreview" :isByd="isByd" :hasCarBrand="item.hasCarBrand" :aitoCarModelIds="aitoCarModelIds" />
</view>
</template>
<template v-if="type != 'preview'">
<template v-if="backZindex">
<template v-if="folderToolList.length > 1">
<template v-if="ui.backZindex">
<template v-if="list.folderToolList.length > 1">
<tool-box
v-for="(folder, idx) in folderToolList"
v-for="(folder, idx) in list.folderToolList"
:key="folder.folderCode"
:ref="'toolRef' + idx"
:data="folderMaterialsMap[folder.folderCode] || []"
:data="list.folderMaterialsMap[folder.folderCode] || []"
:type="type"
@choose="choose"
@finish="open"
......@@ -49,7 +49,7 @@
<template v-else>
<tool-box
ref="toolRef"
:data="pageToolList"
:data="list.pageToolList"
:type="type"
@choose="choose"
@finish="open"
......@@ -59,13 +59,13 @@
:showPayBtn="watchPayInfo"
/>
</template>
<view class="pen-box" @click="drawStatus = !drawStatus">
<view :class="['sprite-icon', `${!drawStatus ? 'icon-pen' : 'icon-pen-active'}`]"></view>
<view class="pen-box" @click="ui.drawStatus = !ui.drawStatus">
<view :class="['sprite-icon', `${!ui.drawStatus ? 'icon-pen' : 'icon-pen-active'}`]"></view>
</view>
</template>
</template>
<finish-step ref="stepRef" @submit="done" :titleTips="finishTips" />
<informationEntry :showPayPage.sync="showPayPage" @finish="open" />
<informationEntry :showPayPage.sync="ui.showPayPage" @finish="open" />
</view>
</template>
<script>
......@@ -109,34 +109,49 @@ export default {
// mixins: [receptionTrackMixin],
data() {
return {
backZindex: 9,
drawStatus: false,
startX: null,
startY: null,
screenWidth: null,
scaleValueObject: {},
showPayPage: false,
productModelStatus: false,
modeName: '',
pageToolList: [],
folderToolList: [],
currentFolderCode: '',
folderMaterialsMap: {},
activeFolderIndex: -1,
moduleList: [],
useCarConfig: false,
dateilKey: Date.now(),
currentMediaId: '',
isAnimating: false,
lastId: null,
animDirection: '',
pendingDirection: '',
// 滑动与动画配置
swipeConfig: {
sensitivity: 12, // 灵敏度系数 (屏幕宽度 / N),值越大越灵敏
verticalLimit: 150, // 垂直防误触阈值 (px)
animDuration: 800 // 动画时长 (ms)
}
// 核心UI状态
ui: {
backZindex: 9,
drawStatus: false,
showPayPage: false,
productModelStatus: false,
activeFolderIndex: -1,
dateilKey: Date.now(),
isAnimating: false,
animDirection: '',
pendingDirection: '',
lastId: null,
},
// 数据列表
list: {
moduleList: [],
pageToolList: [],
folderToolList: [],
folderMaterialsMap: {},
},
// 当前选中项状态
current: {
folderCode: '',
mediaId: '',
modeName: '',
},
// 静态配置(冻结以提升性能)
config: Object.freeze({
swipeConfig: {
sensitivity: 12, // 灵敏度系数 (屏幕宽度 / N),值越大越灵敏
verticalLimit: 150, // 垂直防误触阈值 (px)
animDuration: 800 // 动画时长 (ms)
}
})
}
},
created() {
// 非响应式数据,提升性能
this.touchState = {
startX: 0,
startY: 0,
screenWidth: 0,
scaleValueObject: {}
}
},
computed: {
......@@ -159,14 +174,14 @@ export default {
return this.$store.state.user.historyStatus
},
penSwitch() {
return !this.isPreview && this.drawStatus
return !this.isPreview && this.ui.drawStatus
},
watchPayInfo() {
return this.$store.state.user.paymentType.length ? true : false
},
title() {
let { id } = this,
name = this.moduleList.find(e => e.id == id)?.materialName || ''
name = this.list.moduleList.find(e => e.id == id)?.materialName || ''
return name
},
finishTips() {
......@@ -185,16 +200,36 @@ export default {
},
viewKey() {
return this.$store.state.user.viewKey
},
// 缓存当前索引,避免在 shouldRender 中重复查找 (O(N^2) -> O(N))
currentIndex() {
if (!this.list.moduleList.length) return -1
return this.list.moduleList.findIndex(item => item.id == this.id)
},
// 计算需要渲染的索引集合 (O(1) 查找)
visibleIndices() {
const index = this.currentIndex
if (index === -1) return new Set()
const len = this.list.moduleList.length
// 如果列表很短,直接全部渲染
if (len <= 3) return null
const indices = new Set()
indices.add(index) // 当前
indices.add(index === 0 ? len - 1 : index - 1) // 上一页
indices.add(index === len - 1 ? 0 : index + 1) // 下一页
return indices
}
},
watch: {
watchStatus: {
immediate: true,
handler(newval) {
this.dateilKey = Date.now()
this.pageToolList = this.toolList
this.currentMediaId = this.mediaId
if (newval) this.drawStatus = false
this.ui.dateilKey = Date.now()
this.list.pageToolList = this.toolList
this.current.mediaId = this.mediaId
if (newval) this.ui.drawStatus = false
}
},
viewKey: {
......@@ -206,17 +241,17 @@ export default {
id: {
immediate: true,
handler(newval, oldval) {
if (!this.pageToolList.length) this.pageToolList = this.toolList
if (!this.list.pageToolList.length) this.list.pageToolList = this.toolList
if (this.pendingDirection && oldval) {
this.animDirection = this.pendingDirection;
this.lastId = oldval;
this.isAnimating = true;
this.pendingDirection = '';
if (this.ui.pendingDirection && oldval) {
this.ui.animDirection = this.ui.pendingDirection;
this.ui.lastId = oldval;
this.ui.isAnimating = true;
this.ui.pendingDirection = '';
setTimeout(() => {
this.isAnimating = false;
this.lastId = null;
this.animDirection = '';
this.ui.isAnimating = false;
this.ui.lastId = null;
this.ui.animDirection = '';
}, 500);
}
}
......@@ -224,25 +259,25 @@ export default {
media: {
immediate: true,
handler (val) {
if (Array.isArray(val)) this.moduleList = val
if (Array.isArray(val)) this.list.moduleList = val
}
},
folders: {
immediate: true,
handler (list) {
if (Array.isArray(list) && list.length > 1) {
this.folderToolList = list.map(i => ({
this.list.folderToolList = list.map(i => ({
folderCode: i.folderCode,
typeCode: i.typeCode,
shortTitle: i.directoryName || i.folderCode,
shortTitleUrl: '',
folderName: i.folderName
}))
this.currentFolderCode = this.folderToolList[0]?.folderCode || ''
this.current.folderCode = this.list.folderToolList[0]?.folderCode || ''
this.loadFolderMaterials(list)
} else {
this.folderToolList = []
this.currentFolderCode = ''
this.list.folderToolList = []
this.current.folderCode = ''
}
}
}
......@@ -255,7 +290,7 @@ export default {
},
mounted() {
const systemInfo = uni.getSystemInfoSync()
this.screenWidth = systemInfo.screenWidth
this.touchState.screenWidth = systemInfo.screenWidth
},
methods: {
...mapMutations('audio', ['setReceptionStatus']),
......@@ -263,7 +298,7 @@ export default {
this.$refs.stepRef.open()
},
handleFull(val) {
this.backZindex = val ? 0 : 9
this.ui.backZindex = val ? 0 : 9
},
/**切换素材 */
async choose(e) {
......@@ -277,18 +312,18 @@ export default {
// 计算切换方向
if (e && e.id && this.id != e.id) {
let currentIndex = this.pageToolList.findIndex(item => item.id == this.id)
let nextIndex = this.pageToolList.findIndex(item => item.id == e.id)
let currentIndex = this.list.pageToolList.findIndex(item => item.id == this.id)
let nextIndex = this.list.pageToolList.findIndex(item => item.id == e.id)
if (currentIndex > -1 && nextIndex > -1) {
this.pendingDirection = nextIndex > currentIndex ? 'next' : 'prev'
this.ui.pendingDirection = nextIndex > currentIndex ? 'next' : 'prev'
}
}
// 选择素材:根据素材所属文件夹更新 moduleList,再切换当前素材 id
if (e && e.id) {
const list = (e.folderCode && this.folderMaterialsMap[e.folderCode]) || null
const list = (e.folderCode && this.list.folderMaterialsMap[e.folderCode]) || null
if (Array.isArray(list) && list.length) {
this.moduleList = list.map(item => ({
this.list.moduleList = Object.freeze(list.map(item => ({
...item,
thumbnail: item.materialUrl,
title: item.materialName,
......@@ -300,9 +335,9 @@ export default {
receptionSourceDetailList: {
detailUrl: item.materialUrl
}
}))
this.currentFolderCode = e.folderCode || this.currentFolderCode
this.pageToolList = this.moduleList.map(i => ({ id: i.id, title: i.title }))
})))
this.current.folderCode = e.folderCode || this.current.folderCode
this.list.pageToolList = Object.freeze(this.list.moduleList.map(i => ({ id: i.id, title: i.title })))
}
this.$emit('update:id', e.id)
uni.$logger.local.info(`预览${e.title}`)
......@@ -318,7 +353,7 @@ export default {
this.$emit('back')
},
done(e) {
this.showPayPage = false
this.ui.showPayPage = false
// this.$refs.toolRef.hide()
this.$refs.stepRef.close()
this.$emit('done', e)
......@@ -327,8 +362,8 @@ export default {
this.$refs.pay.show()
},
handleFolderOpen (idx) {
this.activeFolderIndex = idx
const len = this.folderToolList.length
this.ui.activeFolderIndex = idx
const len = this.list.folderToolList.length
for (let i = 0; i < len; i++) {
if (i === idx) continue
const ref = this.$refs['toolRef' + i]
......@@ -340,7 +375,7 @@ export default {
}
},
handleFolderClose (idx) {
if (this.activeFolderIndex === idx) this.activeFolderIndex = -1
if (this.ui.activeFolderIndex === idx) this.ui.activeFolderIndex = -1
},
async loadFolderMaterials (folders = []) {
try {
......@@ -355,30 +390,30 @@ export default {
const map = {}
results.forEach(({ f, res }) => {
const list = Array.isArray(res?.data) ? res.data : []
map[f.folderCode] = list.map(item => ({
map[f.folderCode] = Object.freeze(list.map(item => ({
...item,
shortTitle: item.materialName,
title: item.materialName,
shortTitleUrl: item.materialUrl,
folderCode: f.folderCode
}))
})))
})
this.folderMaterialsMap = map
const filtered = this.folderToolList.filter(f => (this.folderMaterialsMap[f.folderCode] || []).length)
this.folderToolList = filtered
if (this.activeFolderIndex >= filtered.length) this.activeFolderIndex = -1
this.list.folderMaterialsMap = map
const filtered = this.list.folderToolList.filter(f => (this.list.folderMaterialsMap[f.folderCode] || []).length)
this.list.folderToolList = filtered
if (this.ui.activeFolderIndex >= filtered.length) this.ui.activeFolderIndex = -1
if (!filtered.length) {
this.moduleList = []
this.pageToolList = []
this.list.moduleList = []
this.list.pageToolList = []
this.$emit('update:id', '')
return
}
if (!this.moduleList.length) {
if (!this.list.moduleList.length) {
const firstCode = filtered[0].folderCode
const firstList = this.folderMaterialsMap[firstCode] || []
const firstList = this.list.folderMaterialsMap[firstCode] || []
if (firstList.length) {
this.currentFolderCode = firstCode
this.moduleList = firstList.map(item => ({
this.current.folderCode = firstCode
this.list.moduleList = Object.freeze(firstList.map(item => ({
...item,
thumbnail: item.materialUrl,
title: item.materialName,
......@@ -390,9 +425,9 @@ export default {
receptionSourceDetailList: {
detailUrl: item.materialUrl
}
}))
this.pageToolList = this.moduleList.map(i => ({ id: i.id, title: i.title }))
const nextId = +this.moduleList[0].id
})))
this.list.pageToolList = Object.freeze(this.list.moduleList.map(i => ({ id: i.id, title: i.title })))
const nextId = +this.list.moduleList[0].id
this.$emit('update:id', nextId)
}
}
......@@ -400,23 +435,30 @@ export default {
},
calcToolStyle (idx) {
const offset = 140 + idx * 160
const active = this.activeFolderIndex === idx
const active = this.ui.activeFolderIndex === idx
const z = active ? 10000 : 998
return `top: calc(5% + ${offset}rpx); z-index: ${z};`
},
// dbClick () {
// if (!this.isPreview) this.drawStatus = !this.drawStatus
// if (!this.isPreview) this.ui.drawStatus = !this.ui.drawStatus
// },
touchStart(e) {
if (!this.drawStatus && e.changedTouches?.length) {
this.startX = e.changedTouches[0].pageX
this.startY = e.changedTouches[0].pageY
if (!this.ui.drawStatus && e.changedTouches?.length) {
this.touchState.startX = e.changedTouches[0].pageX
this.touchState.startY = e.changedTouches[0].pageY
}
},
touchEnd(e) {
if (this.modeName || this.isAnimating) return
if (this.current.modeName || this.ui.isAnimating) return
const { pageToolList, drawStatus, startX, screenWidth, id, scaleValueObject, productModelStatus } = this
const {
ui: { drawStatus, productModelStatus },
list: { pageToolList },
id,
config: { swipeConfig },
touchState: { startX, startY, screenWidth, scaleValueObject }
} = this
// 快速前置检查
if (!e?.changedTouches?.length || drawStatus || !pageToolList.length) return
......@@ -424,10 +466,10 @@ export default {
const diffX = touch.pageX - startX
// 垂直滑动过大则忽略水平滑动,避免误触
if (Math.abs(this.startY - touch.pageY) > this.swipeConfig.verticalLimit) return
if (Math.abs(startY - touch.pageY) > swipeConfig.verticalLimit) return
// 距离检查
if (Math.abs(diffX) <= screenWidth / this.swipeConfig.sensitivity) return
if (Math.abs(diffX) <= screenWidth / swipeConfig.sensitivity) return
const index = pageToolList.findIndex(item => item.id == id)
if (index === -1) return
......@@ -439,10 +481,10 @@ export default {
let nextIndex
if (isNext) {
nextIndex = index === pageToolList.length - 1 ? 0 : index + 1
this.pendingDirection = 'next'
this.ui.pendingDirection = 'next'
} else {
nextIndex = index === 0 ? pageToolList.length - 1 : index - 1
this.pendingDirection = 'prev'
this.ui.pendingDirection = 'prev'
}
const nextItem = pageToolList[nextIndex]
......@@ -452,33 +494,35 @@ export default {
})
uni.$logger.local.info(`预览${nextItem.title}`)
},
getViewClass(item) {
const isCurrent = item.id == this.id
const isLast = item.id == this.lastId
getViewClass(item, index) {
// 性能优化:直接使用索引比较
const currentIndex = this.currentIndex
const isCurrent = index === currentIndex
const isLast = item.id == this.ui.lastId
if (isCurrent) {
if (this.isAnimating) {
return this.animDirection === 'next' ? 'slide-in-right' : 'slide-in-left'
if (this.ui.isAnimating) {
return this.ui.animDirection === 'next' ? 'slide-in-right' : 'slide-in-left'
}
return 'showView'
}
if (isLast && this.isAnimating) {
return this.animDirection === 'next' ? 'slide-out-left' : 'slide-out-right'
if (isLast && this.ui.isAnimating) {
return this.ui.animDirection === 'next' ? 'slide-out-left' : 'slide-out-right'
}
return ''
},
scale(e) {
let { id } = this
this.scaleValueObject[id] = e
this.touchState.scaleValueObject[id] = e
},
// setPageToolList () {
// if (this.channelType == 1) {
// let { carModelId } = this.customerInfo
// const isAito = this.aitoCarModelIds?.findIndex(e => e == carModelId)
// if (carModelId && isAito == -1) {
// this.pageToolList = this.toolList.filter(e => !e.isAito)
// } else this.pageToolList = this.toolList
// } else this.pageToolList = this.toolList
// this.list.pageToolList = this.toolList.filter(e => !e.isAito)
// } else this.list.pageToolList = this.toolList
// } else this.list.pageToolList = this.toolList
// },
async setPageData() {
......@@ -498,41 +542,29 @@ export default {
}
},
setViewInfo(data) {
let { currentMediaId, id: pageId } = this,
let { current: { mediaId: currentMediaId }, id: pageId } = this,
{ id, moduleList, toolList } = data
const curr = moduleList.find(item => item.id == pageId)
const materialName = curr ? curr.materialName : ''
this.moduleList = moduleList
this.pageToolList = toolList
// 使用 Object.freeze 冻结大对象,减少响应式开销
this.list.moduleList = Object.freeze(moduleList)
this.list.pageToolList = Object.freeze(toolList)
if (id != currentMediaId) {
let jumpItem = moduleList.find(e => e.materialName == materialName)
this.$emit('update:id', jumpItem ? jumpItem.id : moduleList[0].id)
}
this.currentMediaId = id
this.current.mediaId = id
},
// 判断是否应该渲染该组件(性能优化)
shouldRender(item) {
// 如果列表很短,直接全部渲染
if (this.moduleList.length <= 3) return true
const currentIndex = this.moduleList.findIndex(i => i.id == this.id)
if (currentIndex === -1) return false
const targetIndex = this.moduleList.findIndex(i => i.id == item.id)
// 渲染当前页
if (currentIndex === targetIndex) return true
// 渲染上一页(考虑循环)
const prevIndex = currentIndex === 0 ? this.moduleList.length - 1 : currentIndex - 1
if (prevIndex === targetIndex) return true
// 渲染下一页(考虑循环)
const nextIndex = currentIndex === this.moduleList.length - 1 ? 0 : currentIndex + 1
if (nextIndex === targetIndex) return true
return false
shouldRender(index) {
// 如果列表很短,直接全部渲染 (visibleIndices 返回 null)
if (!this.visibleIndices) return true
return this.visibleIndices.has(index)
}
},
beforeDestroy() {
// 清理可能存在的动画定时器
if (this.animTimer) clearTimeout(this.animTimer)
}
}
</script>
......@@ -655,4 +687,4 @@ export default {
transform: translateX(100%);
}
}
</style>
</style>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!