VueUse useWebWorker JS创建多线程任务

VueUse useWebWorker JS创建多线程任务,JavaScript采用的是单线程模型,而Web Worker可以给js创建多线程的环境,那么当需要长时间耗时的任务就可以交给webworker去执行,而主线程就不会被阻塞。

代码示例

import { useWebWorker } from '@vueuse/core'


const { data, post, terminate, worker } = useWebWorker('/path/to/worker.js')
状态类型描述
dataRef<any>通过worker接收到的最新数据的引用,可以观察到对传入消息的响应
workerShallowRef<Worker | undefined>WebWorker实例的引用
方法参数描述
post(data: any) => void给线程发送数据
terminate() => void终止线程

类型定义

type PostMessage = (typeof Worker.prototype)["postMessage"]
export interface UseWebWorkerReturn<Data = any> {
  data: Ref<Data>
  post: PostMessage
  terminate: () => void
  worker: ShallowRef<Worker | undefined>
}
type WorkerFn = (...args: unknown[]) => Worker
/**
 * Simple Web Workers registration and communication.
 *
 * @see https://vueuse.org/useWebWorker
 * @param url
 * @param workerOptions
 * @param options
 */
export declare function useWebWorker<T = any>(
  url: string,
  workerOptions?: WorkerOptions,
  options?: ConfigurableWindow,
): UseWebWorkerReturn<T>
/**
 * Simple Web Workers registration and communication.
 *
 * @see https://vueuse.org/useWebWorker
 * @param worker
 */
export declare function useWebWorker<T = any>(
  worker: Worker | WorkerFn,
): UseWebWorkerReturn<T>