useWebWorkerFn 可以独立于UI主线程运行,当执行耗时长或专用大量消耗计算资源的方法时并不会阻塞UI交互,这样程序交互更顺滑,使用 Promise 语法。
import { useWebWorkerFn } from '@vueuse/core'
const data = ref<number[] | null>(null)
const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(() => {
//在这里执行耗时的代码
const randomNumber = () => Math.trunc(Math.random() * 5_000_00)
const numbers: number[] = Array(5_000_000).fill(undefined).map(randomNumber)
numbers.sort()
return numbers.slice(0, 5)
})
//运行状态
const running = computed(() => workerStatus.value === 'RUNNING')
//获取返回值
data.value = await workerFn()
//停止执行
workerTerminate('PENDING')
也可以这样使用
import { useWebWorkerFn } from '@vueuse/core'
const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(
dates => dates.sort(dateFns.compareAsc),
{
timeout: 50000,
dependencies: [
'https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js', // dateFns
],
},
)
例子
export type WebWorkerStatus =
| "PENDING"
| "SUCCESS"
| "RUNNING"
| "ERROR"
| "TIMEOUT_EXPIRED"
export interface UseWebWorkerOptions extends ConfigurableWindow {
/**
* Number of milliseconds before killing the worker
*
* @default undefined
*/
timeout?: number
/**
* An array that contains the external dependencies needed to run the worker
*/
dependencies?: string[]
}
/**
* Run expensive function without blocking the UI, using a simple syntax that makes use of Promise.
*
* @see https://vueuse.org/useWebWorkerFn
* @param fn
* @param options
*/
export declare function useWebWorkerFn<T extends (...fnArgs: any[]) => any>(
fn: T,
options?: UseWebWorkerOptions,
): {
workerFn: (...fnArgs: Parameters<T>) => Promise<ReturnType<T>>
workerStatus: Ref<WebWorkerStatus>
workerTerminate: (status?: WebWorkerStatus) => void
}
export type UseWebWorkerFnReturn = ReturnType<typeof useWebWorkerFn>