优化滚动 组件

This commit is contained in:
王佑琳 2026-03-27 19:01:00 +08:00
parent 6ff21efb5f
commit ff4ae2bdc8
13 changed files with 1505 additions and 591 deletions

1
auto-imports.d.ts vendored
View File

@ -8,6 +8,7 @@ export {}
declare global {
const EffectScope: typeof import('vue').EffectScope
const ElMessage: typeof import('element-plus/es').ElMessage
const ElMessageBox: typeof import('element-plus/es').ElMessageBox
const ElNotification: typeof import('element-plus/es').ElNotification
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate
const computed: typeof import('vue').computed

3
components.d.ts vendored
View File

@ -11,6 +11,7 @@ export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
2: typeof import('./src/components/virtual-scroller/VirtualScroller copy 2.vue')['default']
Canvas: typeof import('./src/components/canvas/index.vue')['default']
copy: typeof import('./src/components/virtual-scroller/VirtualScroller copy.vue')['default']
DialogBox: typeof import('./src/components/dialogBox/index.vue')['default']
@ -35,5 +36,7 @@ declare module 'vue' {
Select: typeof import('./src/components/Select/index.vue')['default']
Time: typeof import('./src/components/dialogBox/Time/index.vue')['default']
VirtualScroller: typeof import('./src/components/virtual-scroller/VirtualScroller.vue')['default']
'VirtualScroller copy': typeof import('./src/components/virtual-scroller/VirtualScroller copy.vue')['default']
'VirtualScroller copy 2': typeof import('./src/components/virtual-scroller/VirtualScroller copy 2.vue')['default']
}
}

View File

@ -8,4 +8,9 @@ export function getGenerateHistoryList(query) {
// 取消或收藏
export function cancelOrCollect(query) {
return service.post('/collect/toggle', null, { params: query })
}
// 删除生成历史
export function deleteGenerateHistory(query) {
return service.delete('/taskRecordHistory/delete', { params: query })
}

View File

@ -75,7 +75,6 @@ const props = defineProps({
}
})
const emit = defineEmits(['open-canvas'])
const router = useRouter()
const useDisplay = useDisplayStore()
@ -122,6 +121,20 @@ const handleStart = async () => {
imgs.push({ name: `image_${index + 1}`, url: img.url })
})
console.log('imgs', imgs)
const result = {
type: props.type,
model: model.value,
modelType: modelType.value,
prompt: prompt.value,
proportion: proportion.value,
referenceImages: referenceImages.value,
quantity: quantity.value,
resolution: resolution.value,
time: time.value,
videoPattern: videoPattern.value
}
const data = {
AIGC: 'Painting',
platform: 'runninghub',
@ -133,12 +146,32 @@ const handleStart = async () => {
{ name: 'aspect_ratio', data: proportion.value},
{ name: 'resolution', data: resolution.value},
],
imgs
imgs,
result
}
await generate(modelType.value, data)
console.log('生成中', isgerenate.value)
}
const fillParamsFromResult = (resultData) => {
if (!resultData) return
if (resultData.model !== undefined) model.value = resultData.model
if (resultData.modelType !== undefined) modelType.value = resultData.modelType
if (resultData.prompt !== undefined) prompt.value = resultData.prompt
if (resultData.proportion !== undefined) proportion.value = resultData.proportion
if (resultData.referenceImages !== undefined) referenceImages.value = resultData.referenceImages
if (resultData.quantity !== undefined) quantity.value = resultData.quantity
if (resultData.resolution !== undefined) resolution.value = resultData.resolution
if (resultData.time !== undefined) time.value = resultData.time
if (resultData.videoPattern !== undefined) videoPattern.value = resultData.videoPattern
}
defineExpose({
fillParamsFromResult,
handleStart
})
const handleContainerClick = () => {
if (useDisplay.Sender_variant === 'default') {
useDisplay.Sender_variant = 'updown'
@ -151,7 +184,7 @@ const handleScrollToBottom = () => {
}
const handleOpenCanvas = (data) => {
emit('open-canvas', data)
useDisplay.openCanvas(data)
}
watch(() => useDisplay.isSubGerenate, (newValue) => {

View File

@ -0,0 +1,486 @@
<template>
<div class="virtual-scroller" :style="containerStyle">
<div
ref="scrollContainerRef"
class="virtual-scroller-container"
:style="scrollContainerStyle"
@scroll.passive="handleScroll"
@wheel="handleWheel"
>
<div class="virtual-scroller-spacer" :style="spacerStyle"></div>
<div class="virtual-scroller-placeholder" :style="placeholderStyle">
<slot name="bottom-placeholder" />
</div>
<div
v-for="item in visibleItems"
:key="item.key"
:ref="el => setItemRef(el, item.key)"
class="virtual-scroller-item"
:style="getItemStyle(item)"
:data-index="item.index"
:data-key="item.key"
>
<slot name="default" :item="item.data" :index="item.index" />
</div>
</div>
</div>
</template>
<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
const props = defineProps({
data: {
type: Array,
required: true,
default: () => []
},
itemKey: {
type: [String, Function],
default: 'id'
},
estimatedHeight: {
type: Number,
default: 100
},
buffer: {
type: Number,
default: 5
},
placeholderHeight: {
type: Number,
default: 350
}
})
const emit = defineEmits(['scroll', 'scroll-start', 'scroll-end'])
const scrollContainerRef = ref(null)
const itemRefs = new Map()
const itemHeights = ref(new Map())
const resizeObserver = ref(null)
const isScrolling = ref(false)
const scrollTimeout = ref(null)
const getKey = (item, index) => {
if (typeof props.itemKey === 'function') {
return props.itemKey(item, index)
}
if (item && typeof item === 'object') {
return item[props.itemKey] ?? index
}
return index
}
const getItemHeight = (key) => {
return itemHeights.value.get(key) ?? props.estimatedHeight
}
const containerStyle = computed(() => ({
height: '100%',
width: '100%',
position: 'relative',
}))
const scrollContainerStyle = computed(() => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
overflowX: 'hidden',
overflowY: 'auto',
direction: 'rtl',
transform: 'rotate(180deg)'
}))
const totalDataHeight = computed(() => {
let height = 0
for (let i = 0; i < props.data.length; i++) {
const key = getKey(props.data[i], i)
height += getItemHeight(key)
}
return height
})
const totalHeight = computed(() => {
return props.placeholderHeight + totalDataHeight.value
})
const spacerStyle = computed(() => ({
height: `${totalHeight.value}px`,
width: '100%',
flexShrink: 0
}))
const placeholderStyle = computed(() => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: `${props.placeholderHeight}px`,
zIndex: 1,
direction: 'ltr'
}))
const visibleRange = computed(() => {
const count = props.data.length
if (count === 0) {
return { start: 0, end: 0, offset: 0 }
}
const el = scrollContainerRef.value
if (!el) {
return { start: 0, end: Math.min(count - 1, 9), offset: 0 }
}
const scrollTop = el.scrollTop
const viewportHeight = el.clientHeight || 600
const bufferCount = props.buffer
// In inverted scroll (180deg rotation):
// - scrollTop = 0: visual BOTTOM (shows newer data, lower index)
// - scrollTop = max: visual TOP (shows older data, higher index)
// - visibleStart/visibleEnd are offsets in the data area (after placeholder)
const visibleStart = Math.max(0, scrollTop - props.placeholderHeight)
const visibleEnd = visibleStart + viewportHeight
let startIndex = 0
let endIndex = count - 1
let startOffset = 0
let currentOffset = 0
// Find startIndex: first item that ends after visibleStart
for (let i = 0; i < count; i++) {
const key = getKey(props.data[i], i)
const height = getItemHeight(key)
const itemEnd = currentOffset + height
if (itemEnd > visibleStart) {
startIndex = Math.max(0, i - bufferCount)
break
}
currentOffset += height
}
// Calculate startOffset for startIndex
startOffset = 0
for (let i = 0; i < startIndex; i++) {
const key = getKey(props.data[i], i)
startOffset += getItemHeight(key)
}
// Find endIndex: last item that starts before visibleEnd
currentOffset = startOffset
for (let i = startIndex; i < count; i++) {
const key = getKey(props.data[i], i)
const height = getItemHeight(key)
// Check if this item is visible (item starts before visibleEnd)
if (currentOffset >= visibleEnd) {
// This item starts after visibleEnd, so previous item is the last visible
endIndex = Math.min(count - 1, Math.max(startIndex, i - 1 + bufferCount))
break
}
endIndex = i
currentOffset += height
}
return { start: startIndex, end: endIndex, offset: startOffset }
})
const visibleItems = computed(() => {
const { start, end, offset } = visibleRange.value
const items = []
const count = props.data.length
if (count === 0) return items
const safeStart = Math.max(0, start)
const safeEnd = Math.min(count - 1, end)
if (safeStart > safeEnd) return items
let currentOffset = offset + props.placeholderHeight
const seenKeys = new Set()
for (let i = safeStart; i <= safeEnd; i++) {
const data = props.data[i]
if (!data) continue
const key = getKey(data, i)
// Deduplicate by key
if (seenKeys.has(key)) continue
seenKeys.add(key)
const height = getItemHeight(key)
items.push({
data,
index: i,
key,
offset: currentOffset,
height
})
currentOffset += height
}
return items
})
const getItemStyle = (item) => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
transform: `translateY(${item.offset}px)`,
direction: 'ltr',
willChange: 'transform'
})
const setItemRef = (el, key) => {
if (el) {
itemRefs.set(key, el)
} else {
itemRefs.delete(key)
}
}
const measureItem = (key, element) => {
if (!element) return
const target = element.firstElementChild || element
const height = target.getBoundingClientRect().height
if (height > 0 && height !== itemHeights.value.get(key)) {
const newHeights = new Map(itemHeights.value)
newHeights.set(key, height)
itemHeights.value = newHeights
}
}
const setupResizeObserver = () => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
}
resizeObserver.value = new ResizeObserver((entries) => {
for (const entry of entries) {
const key = entry.target.dataset.key
if (key !== undefined) {
measureItem(key, entry.target)
}
}
})
}
const observeItems = () => {
if (!resizeObserver.value) return
resizeObserver.value.disconnect()
for (const [key, element] of itemRefs) {
if (element) {
resizeObserver.value.observe(element)
}
}
}
const handleWheel = (event) => {
if (!scrollContainerRef.value) return
scrollContainerRef.value.scrollBy({
top: -event.deltaY,
behavior: 'instant'
})
event.preventDefault()
}
const handleScroll = (event) => {
const target = event.target
const scrollHeight = target.scrollHeight
const scrollTop = target.scrollTop
const clientHeight = target.clientHeight
isScrolling.value = true
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
}
scrollTimeout.value = setTimeout(() => {
isScrolling.value = false
}, 150)
// In inverted scroll:
// - distanceToTop (visual top) = scrollHeight - scrollTop - clientHeight
// - distanceToBottom (visual bottom) = scrollTop
// - isAtTop (visual top, older data) = distanceToTop <= threshold
// - isAtBottom (visual bottom, newer data) = distanceToBottom <= threshold
const distanceToTop = scrollHeight - scrollTop - clientHeight
const distanceToBottom = scrollTop
const threshold = 5
const isAtTop = distanceToTop <= threshold
const isAtBottom = distanceToBottom <= threshold
emit('scroll', {
scrollTop,
scrollHeight,
clientHeight,
distanceToTop,
distanceToBottom,
isAtTop,
isAtBottom
})
// scroll-start: reached visual top (older data, need to load more)
if (isAtTop) {
emit('scroll-start')
}
// scroll-end: reached visual bottom (newer data)
if (isAtBottom) {
emit('scroll-end')
}
}
const scrollToIndex = (index, behavior = 'auto') => {
if (!scrollContainerRef.value || index < 0 || index >= props.data.length) return
let offset = 0
for (let i = 0; i < index; i++) {
const key = getKey(props.data[i], i)
offset += getItemHeight(key)
}
const targetScrollTop = offset + props.placeholderHeight
scrollContainerRef.value.scrollTo({
top: targetScrollTop,
behavior
})
}
const scrollToBottom = (behavior = 'smooth') => {
if (!scrollContainerRef.value) return
requestAnimationFrame(() => {
if (!scrollContainerRef.value) return
// In inverted scroll, bottom is scrollTop = 0
scrollContainerRef.value.scrollTo({ top: 0, behavior })
})
}
const scrollToTop = (behavior = 'smooth') => {
if (!scrollContainerRef.value) return
requestAnimationFrame(() => {
if (!scrollContainerRef.value) return
// In inverted scroll, top is scrollTop = max
scrollContainerRef.value.scrollTo({
top: scrollContainerRef.value.scrollHeight,
behavior
})
})
}
const getScrollElement = () => scrollContainerRef.value
const isAtTop = () => {
if (!scrollContainerRef.value) return false
const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.value
return scrollHeight - scrollTop - clientHeight <= 5
}
const isAtBottom = () => {
if (!scrollContainerRef.value) return false
return scrollContainerRef.value.scrollTop <= 5
}
const reset = () => {
itemHeights.value = new Map()
itemRefs.clear()
}
watch(() => props.data, (newData, oldData) => {
const newLength = newData?.length || 0
const oldLength = oldData?.length || 0
if (newLength < oldLength) {
reset()
}
nextTick(observeItems)
}, { deep: true })
watch(visibleItems, () => {
nextTick(observeItems)
}, { deep: true })
onMounted(() => {
setupResizeObserver()
nextTick(observeItems)
})
onBeforeUnmount(() => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
}
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
}
itemRefs.clear()
})
defineExpose({
scrollToIndex,
scrollToBottom,
scrollToTop,
getScrollElement,
isAtTop,
isAtBottom,
reset,
scrollContainerRef
})
</script>
<style lang="less" scoped>
.virtual-scroller {
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
-ms-overflow-style: none;
&-container {
contain: layout style;
&::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
}
&-spacer {
flex-shrink: 0;
width: 100%;
}
&-item {
contain: layout style;
backface-visibility: hidden;
perspective: 1000px;
}
&-placeholder {
contain: layout style;
}
}
</style>

View File

@ -0,0 +1,518 @@
<template>
<div class="virtual-scroller" :style="containerStyle">
<div class="virtual-scroller-wrapper" :style="wrapperStyle">
<div
ref="scrollContainerRef"
class="virtual-scroller-container"
:style="containerInnerStyle"
@scroll.passive="handleScroll"
@wheel="handleWheel"
>
<div class="virtual-scroller-spacer" :style="spacerStyle"></div>
<div class="virtual-scroller-placeholder" :style="placeholderStyle">
<slot name="bottom-placeholder" />
</div>
<div
v-for="item in visibleItems"
:key="item.key"
:ref="el => setItemRef(el, item.key)"
class="virtual-scroller-item"
:style="getItemStyle(item)"
:data-index="item.index"
:data-key="item.key"
>
<slot name="default" :item="item.data" :index="item.index" />
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
const props = defineProps({
data: {
type: Array,
required: true,
default: () => []
},
itemKey: {
type: [String, Function],
default: 'id'
},
estimatedHeight: {
type: Number,
default: 100
},
buffer: {
type: Number,
default: 5
},
placeholderHeight: {
type: Number,
default: 350
}
})
const emit = defineEmits(['scroll', 'scroll-start', 'scroll-end'])
const scrollContainerRef = ref(null)
const itemRefs = new Map()
const itemHeights = ref(new Map())
const resizeObserver = ref(null)
const isScrolling = ref(false)
const scrollTimeout = ref(null)
const getKey = (item, index) => {
if (typeof props.itemKey === 'function') {
return props.itemKey(item, index)
}
if (item && typeof item === 'object') {
return item[props.itemKey] ?? index
}
return index
}
const getItemHeight = (key) => {
return itemHeights.value.get(key) ?? props.estimatedHeight
}
const containerStyle = computed(() => ({
height: '100%',
width: '100%',
position: 'relative'
}))
const wrapperStyle = computed(() => ({
height: '100%',
width: '100%',
position: 'relative',
overflow: 'hidden',
transform: 'rotate(180deg)',
direction: 'rtl'
}))
const containerInnerStyle = computed(() => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
overflowX: 'hidden',
overflowY: 'auto',
direction: 'ltr'
}))
const totalDataHeight = computed(() => {
let height = 0
for (let i = 0; i < props.data.length; i++) {
const key = getKey(props.data[i], i)
height += getItemHeight(key)
}
return height
})
const totalHeight = computed(() => {
return props.placeholderHeight + totalDataHeight.value
})
const spacerStyle = computed(() => ({
height: `${totalHeight.value}px`,
width: '100%',
flexShrink: 0
}))
const placeholderStyle = computed(() => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: `${props.placeholderHeight}px`,
zIndex: 1
}))
const getItemOffsets = () => {
const offsets = []
let offset = 0
for (let i = 0; i < props.data.length; i++) {
offsets.push(offset)
const key = getKey(props.data[i], i)
offset += getItemHeight(key)
}
return offsets
}
const visibleRange = computed(() => {
const count = props.data.length
if (count === 0) {
return { start: 0, end: 0, offset: 0 }
}
const el = scrollContainerRef.value
if (!el) {
return { start: 0, end: Math.min(count - 1, 9), offset: 0 }
}
const scrollTop = el.scrollTop
const viewportHeight = el.clientHeight || 600
const bufferCount = props.buffer
// In inverted scroll (180deg rotation):
// - scrollTop = 0: visual BOTTOM (shows newer data, lower index)
// - scrollTop = max: visual TOP (shows older data, higher index)
// - Items are positioned from top: placeholderHeight, then data items
// - visibleStart/visibleEnd are offsets in the data area (after placeholder)
// When scrollTop = 0, we're at visual bottom, showing items near the START of data
// When scrollTop = max, we're at visual top, showing items near the END of data
// The visible area in data coordinates:
// - scrollTop 0 means we see items at offset 0 (start of data)
// - scrollTop increases means we see items at higher offsets (end of data)
const visibleStart = Math.max(0, scrollTop - props.placeholderHeight)
const visibleEnd = visibleStart + viewportHeight
let startIndex = 0
let endIndex = count - 1
let startOffset = 0
let currentOffset = 0
// Find startIndex: first item that ends after visibleStart
for (let i = 0; i < count; i++) {
const key = getKey(props.data[i], i)
const height = getItemHeight(key)
const itemEnd = currentOffset + height
if (itemEnd > visibleStart) {
startIndex = Math.max(0, i - bufferCount)
break
}
currentOffset += height
}
// Calculate startOffset for startIndex
startOffset = 0
for (let i = 0; i < startIndex; i++) {
const key = getKey(props.data[i], i)
startOffset += getItemHeight(key)
}
// Find endIndex: last item that starts before visibleEnd
currentOffset = startOffset
for (let i = startIndex; i < count; i++) {
const key = getKey(props.data[i], i)
const height = getItemHeight(key)
// Check if this item is visible (item starts before visibleEnd)
if (currentOffset >= visibleEnd) {
// This item starts after visibleEnd, so previous item is the last visible
endIndex = Math.min(count - 1, Math.max(startIndex, i - 1 + bufferCount))
break
}
endIndex = i
currentOffset += height
}
return { start: startIndex, end: endIndex, offset: startOffset }
})
const visibleItems = computed(() => {
const { start, end, offset } = visibleRange.value
const items = []
const count = props.data.length
if (count === 0) return items
const safeStart = Math.max(0, start)
const safeEnd = Math.min(count - 1, end)
if (safeStart > safeEnd) return items
let currentOffset = offset + props.placeholderHeight
const seenKeys = new Set()
for (let i = safeStart; i <= safeEnd; i++) {
const data = props.data[i]
if (!data) continue
const key = getKey(data, i)
// Deduplicate by key
if (seenKeys.has(key)) continue
seenKeys.add(key)
const height = getItemHeight(key)
items.push({
data,
index: i,
key,
offset: currentOffset,
height
})
currentOffset += height
}
return items
})
const getItemStyle = (item) => ({
position: 'absolute',
top: 0,
left: 0,
right: 0,
transform: `translateY(${item.offset}px)`,
willChange: 'transform'
})
const setItemRef = (el, key) => {
if (el) {
itemRefs.set(key, el)
} else {
itemRefs.delete(key)
}
}
const measureItem = (key, element) => {
if (!element) return
const target = element.firstElementChild || element
const height = target.getBoundingClientRect().height
if (height > 0 && height !== itemHeights.value.get(key)) {
const newHeights = new Map(itemHeights.value)
newHeights.set(key, height)
itemHeights.value = newHeights
}
}
const setupResizeObserver = () => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
}
resizeObserver.value = new ResizeObserver((entries) => {
for (const entry of entries) {
const key = entry.target.dataset.key
if (key !== undefined) {
measureItem(key, entry.target)
}
}
})
}
const observeItems = () => {
if (!resizeObserver.value) return
resizeObserver.value.disconnect()
for (const [key, element] of itemRefs) {
if (element) {
resizeObserver.value.observe(element)
}
}
}
const handleWheel = (event) => {
if (!scrollContainerRef.value) return
scrollContainerRef.value.scrollBy({
top: -event.deltaY,
behavior: 'instant'
})
event.preventDefault()
}
const handleScroll = (event) => {
const target = event.target
const scrollHeight = target.scrollHeight
const scrollTop = target.scrollTop
const clientHeight = target.clientHeight
isScrolling.value = true
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
}
scrollTimeout.value = setTimeout(() => {
isScrolling.value = false
}, 150)
// In inverted scroll:
// - distanceToTop (visual top) = scrollHeight - scrollTop - clientHeight
// - distanceToBottom (visual bottom) = scrollTop
// - isAtTop (visual top, older data) = distanceToTop <= threshold
// - isAtBottom (visual bottom, newer data) = distanceToBottom <= threshold
const distanceToTop = scrollHeight - scrollTop - clientHeight
const distanceToBottom = scrollTop
const threshold = 5
const isAtTop = distanceToTop <= threshold
const isAtBottom = distanceToBottom <= threshold
emit('scroll', {
scrollTop,
scrollHeight,
clientHeight,
distanceToTop,
distanceToBottom,
isAtTop,
isAtBottom
})
// scroll-start: reached visual top (older data, need to load more)
if (isAtTop) {
emit('scroll-start')
}
// scroll-end: reached visual bottom (newer data)
if (isAtBottom) {
emit('scroll-end')
}
}
const scrollToIndex = (index, behavior = 'auto') => {
if (!scrollContainerRef.value || index < 0 || index >= props.data.length) return
let offset = 0
for (let i = 0; i < index; i++) {
const key = getKey(props.data[i], i)
offset += getItemHeight(key)
}
const targetScrollTop = offset + props.placeholderHeight
scrollContainerRef.value.scrollTo({
top: targetScrollTop,
behavior
})
}
const scrollToBottom = (behavior = 'smooth') => {
if (!scrollContainerRef.value) return
requestAnimationFrame(() => {
if (!scrollContainerRef.value) return
// In inverted scroll, bottom is scrollTop = 0
scrollContainerRef.value.scrollTo({ top: 0, behavior })
})
}
const scrollToTop = (behavior = 'smooth') => {
if (!scrollContainerRef.value) return
requestAnimationFrame(() => {
if (!scrollContainerRef.value) return
// In inverted scroll, top is scrollTop = max
scrollContainerRef.value.scrollTo({
top: scrollContainerRef.value.scrollHeight,
behavior
})
})
}
const getScrollElement = () => scrollContainerRef.value
const isAtTop = () => {
if (!scrollContainerRef.value) return false
const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.value
return scrollHeight - scrollTop - clientHeight <= 5
}
const isAtBottom = () => {
if (!scrollContainerRef.value) return false
return scrollContainerRef.value.scrollTop <= 5
}
const reset = () => {
itemHeights.value = new Map()
itemRefs.clear()
}
watch(() => props.data, (newData, oldData) => {
const newLength = newData?.length || 0
const oldLength = oldData?.length || 0
if (newLength < oldLength) {
reset()
}
nextTick(observeItems)
}, { deep: true })
watch(visibleItems, () => {
nextTick(observeItems)
}, { deep: true })
onMounted(() => {
setupResizeObserver()
nextTick(observeItems)
})
onBeforeUnmount(() => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
}
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
}
itemRefs.clear()
})
defineExpose({
scrollToIndex,
scrollToBottom,
scrollToTop,
getScrollElement,
isAtTop,
isAtBottom,
reset,
scrollContainerRef
})
</script>
<style lang="less" scoped>
.virtual-scroller {
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
-ms-overflow-style: none;
&-wrapper {
contain: content;
}
&-container {
contain: layout style;
&::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
}
&-spacer {
flex-shrink: 0;
width: 100%;
}
&-item {
contain: layout style;
backface-visibility: hidden;
perspective: 1000px;
}
&-placeholder {
contain: layout style;
}
}
</style>

View File

@ -1,613 +1,379 @@
<template>
<div
ref="containerRef"
class="virtual-scroller"
:style="containerStyle"
>
<div class="virtual-scroller" :style="containerStyle">
<div
ref="wrapperRef"
class="virtual-scroller-wrapper"
:style="wrapperStyle"
ref="scrollContainerRef"
class="virtual-scroller-container"
:style="scrollContainerStyle"
@scroll.passive="handleScroll"
>
<div class="virtual-scroller-spacer" :style="spacerStyle"></div>
<div class="virtual-scroller-placeholder" :style="placeholderStyle">
<slot name="bottom-placeholder" />
</div>
<div
ref="renderContainerRef"
class="virtual-scroller-render-container"
:style="renderContainerStyle"
@scroll.passive="handleScroll"
@wheel="handleWheel"
v-for="item in visibleItems"
:key="item.key"
:ref="el => setItemRef(el, item.key)"
class="virtual-scroller-item"
:style="getItemStyle(item)"
:data-index="item.index"
:data-key="item.key"
>
<div class="virtual-scroller-spacer" :style="{ height: `${totalHeight}px` }"></div>
<div
class="virtual-scroller-bottom-placeholder"
:style="bottomPlaceholderStyle"
>
<slot name="bottom-placeholder" />
</div>
<div
v-for="renderItem in visibleItems"
:key="renderItem.key"
:ref="el => setItemRef(el, renderItem.key)"
class="virtual-scroller-item"
:style="getItemStyle(renderItem)"
:data-index="renderItem.index"
:data-key="renderItem.key"
>
<slot
name="default"
:item="renderItem.item"
:index="renderItem.index"
/>
</div>
<slot name="default" :item="item.data" :index="item.index" />
</div>
</div>
</div>
</template>
<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick, type CSSProperties } from 'vue'
const props = defineProps({
data: {
type: Array,
required: true,
default: () => []
},
itemKey: {
type: [String, Function],
default: 'id'
},
estimatedHeight: {
type: Number,
default: 100
},
buffer: {
type: Number,
default: 3
},
height: {
type: [String, Number],
default: '100%'
},
width: {
type: [String, Number],
default: '100%'
},
renderMode: {
type: String,
default: 'default',
validator: (value) => ['default', 'top'].includes(value)
},
bottomPlaceholderHeight: {
type: Number,
default: 350
}
interface VirtualScrollerProps {
items: any[]
estimatedHeight?: number
bufferSize?: number
keyField?: string
height?: string | number
direction?: 'normal' | 'reverse'
}
const props = withDefaults(defineProps<VirtualScrollerProps>(), {
estimatedHeight: 100,
bufferSize: 3,
keyField: 'id',
height: '100%',
direction: 'reverse'
})
const emit = defineEmits(['scroll', 'scroll-start', 'scroll-end'])
const emit = defineEmits<{
scroll: [scrollTop: number, scrollInfo: {
isAtTop: boolean
isAtBottom: boolean
distanceToTop: number
distanceToBottom: number
}]
'visible-change': [startIndex: number, endIndex: number]
}>()
const containerRef = ref(null)
const wrapperRef = ref(null)
const renderContainerRef = ref(null)
const itemRefs = new Map()
const itemHeights = ref(new Map())
const resizeObserver = ref(null)
const scrollContainerRef = ref<HTMLElement | null>(null)
const scrollTop = ref(0)
const isScrolling = ref(false)
const scrollTimeout = ref(null)
const itemRefs = new Map<string, HTMLElement>()
const isReverseMode = computed(() => props.direction === 'reverse')
const isInitializing = ref(true)
const containerStyle = computed(() => ({
height: '100%',
width: '100%',
position: 'relative'
}))
const itemHeights = ref(new Map<string | number, number>())
const itemOffsets = ref(new Map<string | number, number>())
let resizeObserver: ResizeObserver | null = null
const getItemKey = (item, index) => {
if (typeof props.itemKey === 'function') {
return props.itemKey(item, index)
function getItemKey(item: any, index: number): string | number {
return item[props.keyField] ?? index
}
function getItemHeight(key: string | number): number {
return itemHeights.value.get(key) ?? props.estimatedHeight
}
function calculateOffsets() {
let offset = 0
const newOffsets = new Map<string | number, number>()
for (let i = 0; i < props.items.length; i++) {
const key = getItemKey(props.items[i], i)
newOffsets.set(key, offset)
offset += getItemHeight(key)
}
if (typeof props.itemKey === 'string' && item && typeof item === 'object') {
return item[props.itemKey] ?? index
}
return index
itemOffsets.value = newOffsets
}
const totalHeight = computed(() => {
let height = props.bottomPlaceholderHeight
const len = props.data.length
for (let i = 0; i < len; i++) {
const key = getItemKey(props.data[i], i)
const cachedHeight = itemHeights.value.get(key)
height += cachedHeight !== undefined ? cachedHeight : props.estimatedHeight
let height = 0
for (let i = 0; i < props.items.length; i++) {
const key = getItemKey(props.items[i], i)
height += getItemHeight(key)
}
return height
})
const getItemPosition = (index) => {
let offset = 0
for (let i = 0; i < index; i++) {
const key = getItemKey(props.data[i], i)
const cachedHeight = itemHeights.value.get(key)
offset += cachedHeight !== undefined ? cachedHeight : props.estimatedHeight
}
const key = getItemKey(props.data[index], index)
const height = itemHeights.value.get(key) ?? props.estimatedHeight
return { offset, height }
}
const containerStyle = computed<CSSProperties>(() => ({
height: typeof props.height === 'number' ? `${props.height}px` : props.height,
overflow: 'hidden'
}))
const containerHeight = computed(() => {
if (!renderContainerRef.value) return 0
return renderContainerRef.value.clientHeight
})
const scrollContainerStyle = computed<CSSProperties>(() => ({
height: '100%',
overflowY: 'auto',
overflowX: 'hidden',
transform: 'rotate(180deg)',
position: 'relative'
}))
const spacerStyle = computed<CSSProperties>(() => ({
height: `${totalHeight.value}px`,
width: '1px',
pointerEvents: 'none',
position: 'absolute',
top: 0,
left: 0
}))
const placeholderStyle = computed<CSSProperties>(() => ({
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
pointerEvents: 'none'
}))
const visibleRange = computed(() => {
if (props.data.length === 0) {
return { start: 0, end: 0, offset: 0 }
if (!scrollContainerRef.value || props.items.length === 0) {
return { start: 0, end: Math.min(props.bufferSize * 2, props.items.length - 1) }
}
const el = renderContainerRef.value
if (!el) {
const count = props.data.length
return {
start: Math.max(0, count - 10),
end: count - 1,
offset: 0
}
}
const currentScrollTop = el.scrollTop
const viewportHeight = containerHeight.value || el.clientHeight || 600
const bufferCount = props.buffer
const count = props.data.length
const extraBuffer = Math.ceil(viewportHeight / props.estimatedHeight)
const placeholderHeight = props.bottomPlaceholderHeight
const scrollHeight = el.scrollHeight
const maxScrollTop = Math.max(0, scrollHeight - viewportHeight)
const normalizedScrollTop = Math.min(Math.max(0, currentScrollTop), maxScrollTop)
const visibleStart = Math.max(0, normalizedScrollTop)
const visibleEnd = visibleStart + viewportHeight
const containerHeight = scrollContainerRef.value.clientHeight
const scrollTopValue = scrollTop.value
let startIndex = 0
let endIndex = count - 1
let startOffset = 0
let endIndex = props.items.length - 1
let currentOffset = 0
for (let i = 0; i < count; i++) {
const key = getItemKey(props.data[i], i)
const height = itemHeights.value.get(key) ?? props.estimatedHeight
for (let i = 0; i < props.items.length; i++) {
const key = getItemKey(props.items[i], i)
const itemHeight = getItemHeight(key)
const itemEnd = currentOffset + height
if (itemEnd > visibleStart) {
startIndex = Math.max(0, i - bufferCount - extraBuffer)
if (currentOffset + itemHeight > scrollTopValue - props.bufferSize * props.estimatedHeight) {
startIndex = Math.max(0, i - props.bufferSize)
break
}
currentOffset += height
currentOffset += itemHeight
}
startOffset = 0
for (let i = 0; i < startIndex; i++) {
const key = getItemKey(props.data[i], i)
startOffset += itemHeights.value.get(key) ?? props.estimatedHeight
}
currentOffset = startOffset
for (let i = startIndex; i < count; i++) {
const key = getItemKey(props.data[i], i)
const height = itemHeights.value.get(key) ?? props.estimatedHeight
currentOffset = 0
for (let i = 0; i < props.items.length; i++) {
const key = getItemKey(props.items[i], i)
const itemHeight = getItemHeight(key)
if (currentOffset > visibleEnd) {
endIndex = Math.min(count - 1, i - 1 + bufferCount + extraBuffer)
if (currentOffset > scrollTopValue + containerHeight + props.bufferSize * props.estimatedHeight) {
endIndex = Math.min(props.items.length - 1, i + props.bufferSize)
break
}
currentOffset += height
endIndex = i
currentOffset += itemHeight
}
return { start: startIndex, end: endIndex, offset: startOffset }
return { start: startIndex, end: endIndex }
})
const visibleItems = computed(() => {
const { start, end, offset } = visibleRange.value
const items = []
if (!props.data || props.data.length === 0) {
return []
}
const safeStart = Math.max(0, start)
const safeEnd = Math.min(props.data.length - 1, end)
if (safeStart > safeEnd) {
return []
}
let currentOffset = offset
const seenKeys = new Set()
for (let i = safeStart; i <= safeEnd; i++) {
const item = props.data[i]
const { start, end } = visibleRange.value
const items: Array<{ key: string | number; data: any; index: number; offset: number }> = []
const currentRenderedKeys = new Set<string | number>()
for (let i = start; i <= end; i++) {
const item = props.items[i]
if (!item) continue
const key = getItemKey(item, i)
if (seenKeys.has(key)) continue
seenKeys.add(key)
const cachedHeight = itemHeights.value.get(key)
const height = cachedHeight !== undefined ? cachedHeight : props.estimatedHeight
if (currentRenderedKeys.has(key)) {
continue
}
currentRenderedKeys.add(key)
const offset = itemOffsets.value.get(key) ?? i * props.estimatedHeight
items.push({
item,
key: String(key),
data: item,
index: i,
key,
offset: currentOffset,
height
offset
})
currentOffset += height
}
return items
})
const wrapperStyle = computed(() => ({
direction: 'rtl',
height: '100%',
position: 'relative',
scrollbarWidth: 'auto',
overflow: 'hidden',
transform: 'rotate(180deg)',
width: '100%'
}))
function getItemStyle(item: { offset: number }): CSSProperties {
return {
position: 'absolute',
top: `${item.offset}px`,
left: 0,
right: 0
}
}
const renderContainerStyle = computed(() => ({
direction: 'ltr',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
bottom: 0,
left: 0,
overflowX: 'hidden',
overflowY: 'auto',
position: 'absolute',
right: 0,
top: 0,
width: '100%'
}))
const bottomPlaceholderStyle = computed(() => ({
position: 'absolute',
left: 0,
right: 0,
top: 0,
width: '100%',
height: `${props.bottomPlaceholderHeight}px`,
zIndex: 1
}))
const getItemStyle = (renderItem) => ({
position: 'absolute',
left: 0,
right: 0,
top: 0,
width: '100%',
transform: `translateY(${renderItem.offset}px)`,
willChange: 'transform'
})
const setItemRef = (el, key) => {
function setItemRef(el: any, key: string) {
if (el) {
itemRefs.set(key, el)
itemRefs.set(key, el as HTMLElement)
} else {
itemRefs.delete(key)
}
}
const measureItem = (key, element) => {
if (!element) return
function measureItems() {
if (!resizeObserver) return
const firstChild = element.firstElementChild
const targetElement = firstChild || element
const height = targetElement.getBoundingClientRect().height
if (height > 0) {
const cachedHeight = itemHeights.value.get(key)
if (cachedHeight !== height) {
const newHeights = new Map(itemHeights.value)
newHeights.set(key, height)
itemHeights.value = newHeights
}
}
}
const setupResizeObserver = () => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
}
resizeObserver.value = new ResizeObserver((entries) => {
for (const entry of entries) {
const key = entry.target.dataset.key
if (key !== undefined) {
measureItem(key, entry.target)
}
}
itemRefs.forEach((el, key) => {
resizeObserver!.observe(el)
})
}
const handleWheel = (event) => {
if (!renderContainerRef.value) return
const { deltaY } = event
const el = renderContainerRef.value
el.scrollBy({
top: -deltaY,
behavior: 'instant'
})
event.preventDefault()
function updateItemHeight(key: string | number, height: number) {
const oldHeight = itemHeights.value.get(key)
if (oldHeight !== height) {
itemHeights.value.set(key, height)
calculateOffsets()
}
}
const handleScroll = (event) => {
const target = event.target
const scrollHeight = target.scrollHeight
function handleScroll(event: Event) {
const target = event.target as HTMLElement
const currentScrollTop = target.scrollTop
const viewportHeight = target.clientHeight
scrollTop.value = currentScrollTop
const visualScrollBottom = scrollHeight - currentScrollTop - viewportHeight
scrollTop.value = visualScrollBottom
isScrolling.value = true
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
if (!scrollContainerRef.value) {
emit('scroll', currentScrollTop)
return
}
scrollTimeout.value = setTimeout(() => {
isScrolling.value = false
}, 150)
const containerHeight = scrollContainerRef.value.clientHeight
const maxScroll = Math.max(0, totalHeight.value - containerHeight)
const st = target.scrollTop
const sh = target.scrollHeight
const ch = target.clientHeight
const distanceToTop = currentScrollTop
const distanceToBottom = maxScroll - currentScrollTop
const distanceToContainerTop = st
const distanceToContainerBottom = sh - st - ch
const isAtTop = currentScrollTop >= maxScroll - 10
const isAtBottom = currentScrollTop <= 10
const distanceToPageTop = distanceToContainerBottom
const distanceToPageBottom = distanceToContainerTop
const threshold = 5
const isAtPageTop = distanceToPageTop <= threshold
const isAtPageBottom = distanceToPageBottom <= threshold
emit('scroll', {
target,
scrollTop: visualScrollBottom,
scrollHeight,
clientHeight: ch,
distanceToPageTop,
distanceToPageBottom,
isAtPageTop,
isAtPageBottom
emit('scroll', currentScrollTop, {
isAtTop,
isAtBottom,
distanceToTop,
distanceToBottom
})
}
function scrollToIndex(index: number) {
if (!scrollContainerRef.value) return
if (isAtPageTop) {
emit('scroll-start')
let targetTop = 0
for (let i = 0; i < index; i++) {
const key = getItemKey(props.items[i], i)
targetTop += getItemHeight(key)
}
if (isAtPageBottom) {
emit('scroll-end')
}
scrollContainerRef.value.scrollTop = targetTop
scrollTop.value = targetTop
}
const scrollToIndex = (index, behavior = 'auto') => {
if (!renderContainerRef.value || index < 0 || index >= props.data.length) return
const position = getItemPosition(index)
const el = renderContainerRef.value
const scrollHeight = el.scrollHeight
const targetScrollTop = scrollHeight - position.offset - props.bottomPlaceholderHeight - el.clientHeight
el.scrollTo({
top: targetScrollTop,
behavior
})
function scrollToTop() {
if (!scrollContainerRef.value) return
const containerHeight = scrollContainerRef.value.clientHeight
const maxScroll = Math.max(0, totalHeight.value - containerHeight)
scrollContainerRef.value.scrollTop = maxScroll
scrollTop.value = maxScroll
}
const scrollToBottom = (behavior = 'smooth') => {
if (!renderContainerRef.value) return
requestAnimationFrame(() => {
if (!renderContainerRef.value) return
renderContainerRef.value.scrollTo({
top: 0,
behavior
})
})
}
const scrollToTop = (behavior = 'smooth') => {
if (!renderContainerRef.value) return
requestAnimationFrame(() => {
if (!renderContainerRef.value) return
const scrollHeight = renderContainerRef.value.scrollHeight
renderContainerRef.value.scrollTo({
top: scrollHeight,
behavior
})
})
}
const getScrollElement = () => renderContainerRef.value
const getVisibleIndices = () => {
const { start, end } = visibleRange.value
return Array.from({ length: end - start + 1 }, (_, i) => start + i)
}
const resetMeasurements = () => {
itemHeights.value = new Map()
itemRefs.clear()
function scrollToBottom() {
if (!scrollContainerRef.value) return
scrollContainerRef.value.scrollTop = 0
scrollTop.value = 0
}
const isAtPageBottom = () => {
if (!renderContainerRef.value) return false
const { scrollTop } = renderContainerRef.value
return scrollTop <= 5
}
watch(
() => visibleRange.value,
(newRange) => {
emit('visible-change', newRange.start, newRange.end)
nextTick(() => {
measureItems()
})
},
{ deep: true }
)
const isAtPageTop = () => {
if (!renderContainerRef.value) return false
const { scrollTop, scrollHeight, clientHeight } = renderContainerRef.value
return scrollHeight - scrollTop - clientHeight <= 5
}
watch(
() => props.items,
() => {
calculateOffsets()
nextTick(() => {
measureItems()
})
},
{ immediate: true }
)
const observeVisibleItems = () => {
if (!resizeObserver.value) return
resizeObserver.value.disconnect()
for (const [key, element] of itemRefs) {
if (element) {
resizeObserver.value.observe(element)
watch(
() => props.items.length,
async (newLength, oldLength) => {
if (isReverseMode.value && newLength > (oldLength || 0)) {
await nextTick()
scrollToBottom()
}
}
}
watch(() => props.data, (newData, oldData) => {
const newLength = newData?.length || 0
const oldLength = oldData?.length || 0
if (newLength > oldLength) {
nextTick(() => {
observeVisibleItems()
})
} else if (newLength < oldLength) {
itemHeights.value = new Map()
itemRefs.clear()
nextTick(() => {
observeVisibleItems()
})
} else {
const oldKeys = new Set()
const newKeys = new Set()
for (let i = 0; i < oldLength; i++) {
oldKeys.add(getItemKey(oldData[i], i))
}
for (let i = 0; i < newLength; i++) {
newKeys.add(getItemKey(newData[i], i))
}
let hasChanges = false
for (const key of newKeys) {
if (!oldKeys.has(key)) {
hasChanges = true
break
}
}
if (hasChanges) {
itemHeights.value = new Map()
itemRefs.clear()
nextTick(() => {
observeVisibleItems()
})
}
}
}, { deep: true })
watch(visibleItems, () => {
nextTick(() => {
observeVisibleItems()
})
}, { deep: true })
)
onMounted(() => {
setupResizeObserver()
nextTick(() => {
observeVisibleItems()
resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const el = entry.target as HTMLElement
const key = el.dataset.key
if (key) {
updateItemHeight(key, entry.contentRect.height)
}
}
})
if (scrollContainerRef.value && isReverseMode.value) {
nextTick(() => {
scrollToBottom()
setTimeout(() => {
isInitializing.value = false
}, 100)
})
} else {
isInitializing.value = false
}
measureItems()
})
onBeforeUnmount(() => {
if (resizeObserver.value) {
resizeObserver.value.disconnect()
onUnmounted(() => {
if (resizeObserver) {
resizeObserver.disconnect()
resizeObserver = null
}
if (scrollTimeout.value) {
clearTimeout(scrollTimeout.value)
}
itemRefs.clear()
})
defineExpose({
scrollToIndex,
scrollToBottom,
scrollToTop,
getScrollElement,
getVisibleIndices,
resetMeasurements,
containerRef,
isAtPageBottom,
isAtPageTop
scrollToBottom,
getScrollTop: () => scrollTop.value,
getVisibleRange: () => visibleRange.value,
updateLayout: () => {
calculateOffsets()
measureItems()
}
})
</script>
<style lang="less" scoped>
<style scoped>
.virtual-scroller {
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
-ms-overflow-style: none;
.virtual-scroller-wrapper {
contain: content;
}
.virtual-scroller-spacer {
flex-shrink: 0;
width: 100%;
}
.virtual-scroller-render-container {
contain: layout style;
&::-webkit-scrollbar {
// transform: rotate(180deg);
display: none;
width: 0;
height: 0;
}
}
.virtual-scroller-item {
contain: layout style;
backface-visibility: hidden;
perspective: 1000px;
}
.virtual-scroller-bottom-placeholder {
contain: layout style;
}
position: relative;
width: 100%;
}
.virtual-scroller-container {
position: relative;
width: 100%;
}
.virtual-scroller-spacer {
flex-shrink: 0;
}
.virtual-scroller-item {
will-change: transform;
contain: layout style;
}
</style>

View File

@ -29,49 +29,47 @@ const router = createRouter({
routes
})
// router.beforeEach(async (to, from) => {
// if(to.query.token){
// setToken(to.query.token)
// } else {
// // 检查是否有 token
// const token = getToken()
// if (!token) {
// // 没有 token重定向到登录页
// return '/login'
// }
// }
router.beforeEach(async (to, from) => {
if(to.query.token){
setToken(to.query.token)
} else {
// 检查是否有 token
const token = getToken()
if (!token) {
// 没有 token重定向到登录页
return '/login'
}
}
// // 白名单路径(不需要验证 token 的路径)
// const whiteList = ['/login']
// // 获取用户 store 实例
// const userStore = useUserStore()
// // 如果访问的是白名单路径,直接放行
// if (whiteList.includes(to.path)) {
// return true
// }
// 白名单路径(不需要验证 token 的路径)
const whiteList = ['/login']
// 获取用户 store 实例
const userStore = useUserStore()
// 如果访问的是白名单路径,直接放行
if (whiteList.includes(to.path)) {
return true
}
// // 检查 token 是否有效
// try {
// const isTokenValid = await userStore.checkTokenValid()
// console.log(isTokenValid)
// if (isTokenValid) {
// // token 有效,允许访问
// if (!userStore.userInfo.id) {
// // 如果用户信息不存在,则从服务器获取
// await userStore.getInfo()
// }
// return true
// } else {
// // token 无效,重定向到登录页
// return '/login'
// }
// } catch (error) {
// // 验证过程中出错,重定向到登录页
// console.error('验证 token 时出错:', error)
// return '/login'
// }
// })
router.beforeEach(async (to, from) => {return true})
// 检查 token 是否有效
try {
const isTokenValid = await userStore.checkTokenValid()
console.log(isTokenValid)
if (isTokenValid) {
// token 有效,允许访问
if (!userStore.userInfo.id) {
// 如果用户信息不存在,则从服务器获取
await userStore.getInfo()
}
return true
} else {
// token 无效,重定向到登录页
return '/login'
}
} catch (error) {
// 验证过程中出错,重定向到登录页
console.error('验证 token 时出错:', error)
return '/login'
}
})
export default router

View File

@ -6,6 +6,13 @@ const DisplayStoreSetup = () => {
const currentPage = ref(0)
const hasMoreData = ref(true)
const isLoading = ref(false)
const currentResultData = ref(null)
const dialogBoxRef = ref(null)
const canvasVisible = ref(false)
const canvasImage = ref('')
const canvasReferenceImages = ref([])
const canvasSource = ref('')
const addGeneratingItem = (item) => {
const newItem = {
@ -49,6 +56,13 @@ const DisplayStoreSetup = () => {
hasMoreData.value = true
isLoading.value = false
}
const deleteHistoryItem = (id) => {
const index = tempList.value.findIndex(item => item.id === id)
if (index !== -1) {
tempList.value.splice(index, 1)
}
}
const scrollToBottom = async () => {
const refValue = scrollerRef.value
@ -80,6 +94,40 @@ const DisplayStoreSetup = () => {
console.error('滚动出错:', error)
}
}
const setResultData = (data) => {
currentResultData.value = data
}
const setDialogBoxRef = (ref) => {
dialogBoxRef.value = ref
}
const triggerGenerateWithResult = async () => {
if (dialogBoxRef.value && currentResultData.value) {
await dialogBoxRef.value.fillParamsFromResult(currentResultData.value)
await dialogBoxRef.value.handleStart()
}
}
const fillParamsForEdit = () => {
if (dialogBoxRef.value && currentResultData.value) {
dialogBoxRef.value.fillParamsFromResult(currentResultData.value)
}
}
const openCanvas = (data) => {
if (typeof data === 'string') {
canvasImage.value = data
canvasReferenceImages.value = []
canvasSource.value = ''
} else {
canvasImage.value = data.mainImage?.url || data.mainImage || ''
canvasReferenceImages.value = data.referenceImages || []
canvasSource.value = data.source || ''
}
canvasVisible.value = true
}
return {
Sender_variant,
@ -89,13 +137,25 @@ const DisplayStoreSetup = () => {
currentPage,
hasMoreData,
isLoading,
currentResultData,
dialogBoxRef,
canvasVisible,
canvasImage,
canvasReferenceImages,
canvasSource,
addGeneratingItem,
updateItemToSuccess,
initHistoryList,
prependHistoryList,
appendHistoryList,
resetPagination,
scrollToBottom
scrollToBottom,
deleteHistoryItem,
setResultData,
setDialogBoxRef,
triggerGenerateWithResult,
fillParamsForEdit,
openCanvas
}
}

View File

@ -104,7 +104,8 @@ export async function generate(type, data) {
taskId: taskId,
text: data.prompt || '生成中...',
name: data.prompt || '生成中...',
type: type
type: type,
result: data.result
})
setTimeout(() => {
useDisplay.scrollToBottom()

View File

@ -75,7 +75,7 @@
</div>
<div v-if="props.item.status === 'success'" class="bottom-btn-group">
<div v-for="(item, index) in bottomBtnGroup" :key="index" class="bottom-btn" @click="item.click(file, index)">
<div v-for="(item, index) in bottomBtnGroup" :key="index" class="bottom-btn" @click="item.click()">
<img :src="item.icon" />
<span>{{ item.name }}</span>
</div>
@ -94,7 +94,7 @@ import reEditIcon from '@/assets/display/reEdit.svg'
import againGenerateIcon from '@/assets/display/againGenerate.svg'
import deleteImageIcon from '@/assets/display/deleteImage.svg'
import Img from '@/components/Img/index.vue'
import { cancelOrCollect } from '@/apis/display'
import { cancelOrCollect, deleteGenerateHistory } from '@/apis/display'
const props = defineProps({
item: {
@ -103,7 +103,7 @@ const props = defineProps({
}
})
const emit = defineEmits(['open-canvas'])
const emit = defineEmits(['open-canvas', 'delete-success'])
const useDisplay = useDisplayStore()
const useParams = useParamStore()
@ -131,19 +131,45 @@ const AIbrush = (file, index) => {
})
}
const reEdit = (url, number) => {
console.log(number)
const reEdit = () => {
useDisplay.setResultData(props.item.result)
useDisplay.fillParamsForEdit()
}
const againGenerate = (url, number) => {
console.log(number)
const againGenerate = () => {
useDisplay.setResultData(props.item.result)
useDisplay.triggerGenerateWithResult()
}
const deleteImage = (url, number) => {
console.log(number)
const deleteImage = () => {
ElMessageBox.confirm(
'确定要删除该批次图片吗?此操作不可恢复!',
'删除确认',
{
confirmButtonText: '确定删除',
cancelButtonText: '取消',
type: 'warning',
confirmButtonClass: 'el-button--danger'
}
).then(async () => {
try {
const res = await deleteGenerateHistory({
id: props.item.id
})
if (res.success) {
ElMessage.success('删除成功')
emit('delete-success', props.item.id)
} else {
ElMessage.error(res.message || '删除失败')
}
} catch (error) {
console.error('删除操作失败:', error)
ElMessage.error('删除操作失败')
}
}).catch(() => {})
}
const bottomBtnGroup = [
const bottomBtnGroup = computed(() => [
{
name: '重新编辑',
icon: reEditIcon,
@ -159,7 +185,7 @@ const bottomBtnGroup = [
icon: deleteImageIcon,
click: deleteImage
}
]
])
const addCollection = async (url) => {
try {

View File

@ -45,16 +45,20 @@
<VirtualScroller
ref="scrollerRef"
v-if="props.if"
:data="list"
:item-key="'id'"
:items="list"
key-field="id"
:estimated-height="300"
:render-mode="'top'"
:buffer="2"
:buffer-size="3"
direction="reverse"
class="scroller"
@scroll="handleScroll"
@visible-change="handleVisibleChange"
>
<template #default="{ item, index }">
<Set :key="item.id" :item="item" @open-canvas="openCanvas" />
<Set :key="item.id" :item="item" @open-canvas="openCanvas" @delete-success="handleDeleteSuccess" />
</template>
<template #bottom-placeholder>
<div style="height: 350px;"></div>
</template>
</VirtualScroller>
</div>
@ -96,10 +100,7 @@ const scrollerRef = ref(null)
const isLoadingMoreLocked = ref(false)
const activeTab = ref('all')
const isInitializing = ref(true)
const canvasVisible = ref(false)
const canvasImage = ref('')
const canvasReferenceImages = ref([])
const canvasSource = ref('')
const { canvasVisible, canvasImage, canvasReferenceImages, canvasSource } = storeToRefs(useDisplay)
const chargeType = computed(() => getChargeType(props.type))
console.log(chargeType.value)
@ -137,14 +138,20 @@ const conversion = (newlist) => {
const temp = newlist.list.map((item) => {
const files = item.fileUrl ? item.fileUrl.split(',').filter(url => url.trim()) : []
return {
id: item.taskId,
id: item.id,
taskId: item.taskId,
collection: item.collection,
status: 'success',
prompt: item.prompt,
params: item.params,
result: item.result,
time: item.createTime,
files: files,
collectStatus: item.collectStatus || {}
collectStatus: item.collectStatus || {},
model: item.model || '',
proportion: item.proportion || '',
resolution: item.resolution || '',
quantity: item.quantity || 1
}
})
return temp
@ -237,12 +244,13 @@ const fetchHistory = async (isLoadMore = false) => {
}
}
const handleScroll = (event) => {
const handleScroll = (scrollTop, scrollInfo) => {
if (isInitializing.value) return
const { distanceToPageTop, distanceToPageBottom, isAtPageTop, isAtPageBottom } = event
if (!scrollInfo) return
const { isAtTop, isAtBottom, distanceToTop, distanceToBottom } = scrollInfo
if (isAtPageTop && !isLoading.value && !isLoadingMoreLocked.value && hasMoreData.value) {
if (isAtTop && !isLoading.value && !isLoadingMoreLocked.value && hasMoreData.value) {
isLoadingMoreLocked.value = true
fetchHistory(true)
setTimeout(() => {
@ -250,24 +258,22 @@ const handleScroll = (event) => {
}, 3000)
}
if (isAtPageBottom) {
if (isAtBottom) {
useDisplay.Sender_variant = 'updown'
} else if (distanceToPageTop >= 350) {
} else if (distanceToTop >= 350) {
useDisplay.Sender_variant = 'default'
}
}
const handleVisibleChange = (startIndex, endIndex) => {
}
const handleScrollStart = () => {}
const handleScrollEnd = () => {}
const openCanvas = (data) => {
if (typeof data === 'string') {
canvasImage.value = data
canvasReferenceImages.value = []
canvasSource.value = ''
} else {
canvasImage.value = data.mainImage?.url || data.mainImage || ''
canvasReferenceImages.value = data.referenceImages || []
canvasSource.value = data.source || ''
}
canvasVisible.value = true
useDisplay.openCanvas(data)
}
const handleCanvasSend = (data) => {
@ -285,6 +291,10 @@ const handleExit = () => {
}
}
const handleDeleteSuccess = (id) => {
useDisplay.deleteHistoryItem(id)
}
onMounted(() => {
if (!props.loading) return
refreshing.value = true

View File

@ -1,20 +1,27 @@
<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import display from './display/index.vue'
import Canvas from '@/components/canvas/index.vue'
import { useDisplayStore } from '@/stores'
const route = useRoute()
const useDisplay = useDisplayStore()
const dialogBoxRef = ref(null)
const shouldShowDisplay = computed(() => route.path === '/home')
const loading = computed(() => route.query.loading ? false : (route.path === '/home'))
const Generate = computed(() => route.query.Generate || false)
const type = computed(() => route.query.type || 'painting')
console.log(type.value)
onMounted(() => {
useDisplay.setDialogBoxRef(dialogBoxRef.value)
})
</script>
<template>
<div class="app-container">
<dialogBox :is-generate="shouldShowDisplay" :type="type" :generate="Generate" :loading="loading" @open-canvas="handleOpenCanvas" />
<dialogBox ref="dialogBoxRef" :is-generate="shouldShowDisplay" :type="type" :generate="Generate" :loading="loading" />
<display :if="shouldShowDisplay" :type="type" :loading="loading" />
</div>