Skip to content

useWebWorkerFn

使用 Promise 的简单语法运行昂贵的函数而不阻塞 UI。alewin/useWorker 端口。

¥Run expensive functions without blocking the UI, using a simple syntax that makes use of Promise. A port of alewin/useWorker.

示例

Current Time: 2024-11-02 16:30:07 727

This is a demo showing sort for large array (5 million numbers) with or w/o WebWorker.
Clock stops when UI blocking happens.

用法

¥Usage

基本示例

¥Basic example

js
import { useWebWorkerFn } from '@vueuse/core'

const { workerFn } = useWebWorkerFn(() => {
  // some heavy works to do in web worker
})

使用依赖

¥With dependencies

ts
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
    ],
  },
)

使用本地依赖

¥With local dependencies

ts
import { useWebWorkerFn } from '@vueuse/core'

const pow = (a: number) => a * a

const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(
  numbers => pow(numbers),
  {
    timeout: 50000,
    localDependencies: [pow]
  },
)
js
import { useWebWorkerFn } from '@vueuse/core'
const pow = (a) => a * a
const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(
  (numbers) => pow(numbers),
  {
    timeout: 50000,
    localDependencies: [pow],
  },
)

网络工作者

¥Web Worker

在开始使用此函数之前,我们建议你阅读 网络工作者 文档。

¥Before you start using this function, we suggest you read the Web Worker documentation.

信用

¥Credit

该函数是 Alessio Koci 对 https://github.com/alewin/useWorker 的 Vue 移植,借助 @Donskelle 进行迁移。

¥This function is a Vue port of https://github.com/alewin/useWorker by Alessio Koci, with the help of @Donskelle to migration.

类型声明

显示类型声明
typescript
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[]
  /**
   * An array that contains the local dependencies needed to run the worker
   */
  localDependencies?: Function[]
}
/**
 * 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, WebWorkerStatus>
  workerTerminate: (status?: WebWorkerStatus) => void
}
export type UseWebWorkerFnReturn = ReturnType<typeof useWebWorkerFn>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号