import { ref, shallowRef, watch, toRaw, nextTick, onBeforeUnmount } from 'vue' import type { ShallowRef } from 'vue' type PageList = { name: string; shopList: Shop[] } /** * @param {array} totalList 分页数据源 * @param {*} scroll 滚动组件的实例 * @return {*} { scrollEnd, pageList, loaded } */ export const usePage = (totalList: ShallowRef, scroll: any) => { if (typeof Worker === 'undefined') { alert('抱歉,当前运行环境不支持Web Worker API, 请升级浏览器版本') } const pageList = shallowRef([]) //用于UI渲染的列表 const loaded = ref(false) const worker = shallowRef() worker.value = new Worker('./static/worker/page.worker.js') worker.value.onmessage = e => { pageList.value = e.data.pageList loaded.value = e.data.loaded if (e.data.refresh) { nextTick(() => { scroll.value?.scrollTo?.(0, 0, 100) }) } } function scrollEnd() { worker.value?.postMessage('scrollEnd') } watch(totalList, newVal => { const rawList = newVal.map(item => toRaw(item)) worker.value?.postMessage(rawList) }) onBeforeUnmount(() => { worker.value?.terminate() }) return { scrollEnd, pageList, loaded } }