A Complete Guide to Using vue-worker for Multithreaded Processing in Vue.js
Overview
vue-worker is a lightweight wrapper library that simplifies Web Worker integration for Vue.js applications. It abstracts away the complexity of native Web Worker configuration, exposing a simple, promise-based API to offload heavy computational tasks to a separate background thread, preventing UI blocking and improving application performance.
Installation
First, install the package via npm:
npm install vue-worker --save
Global Setup
Register the plugin in your application's entry file (usually main.js):
import Vue from 'vue'
import VueWorker from 'vue-worker'
Vue.use(VueWorker)
Once registered, you can access the worker API across all your Vue components via this.$worker.
Core API Usage
1. One-off Worker Task with run()
The run() method executes a single, disposable worker task. It automatically terminates the worker thread once the task completes, and returns a Promise that resolves to the task's return value.
- First parameter: The handler function to run in the isolated worker thread
- Second parameter: An array of arguments to pass to the handler function
// Offload heavy arithmetic to a background thread
this.$worker.run((baseNumber, additionalValue) => baseNumber + 10 + additionalValue, [2, 10])
.then(result => {
console.log('Computation result:', result) // Output: 22
})
.catch(error => {
console.error('Worker task failed:', error)
})
2. Persistent Worker with create()
For repeated task execution, use create() to initialize a long-running worker instance that retains registered tasks across multiple calls. It accepts an array of task definition objects, each containing a unique message ID and a corresponding handler func.
// Define reusable worker tasks
const workerTaskList = [
{
message: 'echoInput',
func: (inputPayload) => inputPayload
},
{
message: 'processLargeDataset',
func: (rawDataset) => {
// Simulate heavy data processing logic
return rawDataset.filter(item => item.isActive).map(item => item.formattedValue)
}
}
]
// Initialize persistent worker instance
this.persistentWorker = this.$worker.create(workerTaskList)
Trigger Tasks with postMessage()
postMessage() is a method of the persistent worker instance, used to trigger a specific registered task. It returns a Promise that resolves to the task's output.
- First parameter: The
messageID of the task to trigger - Second parameter: Arguments to pass to the task's handler function
// Trigger the echoInput task with sample payload
this.persistentWorker.postMessage('echoInput', [{ userName: 'Lily', age: 25 }])
.then(response => {
console.log('Task response:', response)
})
Batch Trigger Tasks with postAll()
The postAll() method lets you trigger multiple tasks at the same time. It accepts the following input types:
- No parameters: Triggers all registered tasks
- String: Triggers all tasks matching the givan
messageID - Array of objects: Each object specifies a task
messageID and correspondingargsto pass
// Trigger multiple tasks with custom arguments
this.persistentWorker.postAll([
{ message: 'echoInput', args: ['Sample test input'] },
{ message: 'processLargeDataset', args: [[{isActive: true, formattedValue: 12}, {isActive: false, formattedValue: 34}]] }
])
.then(([echoResult, processedData]) => {
console.log('Echo output:', echoResult)
console.log('Processed dataset:', processedData)
})
// Trigger all instances of a single task
this.persistentWorker.postAll('echoInput')
.then(results => {
console.log('All echo task results:', results)
})
3. Dynamic Task Management
Register New Tasks
Use the register() method to add new tasks to an existing persistent worker at runtime:
// Add a new sum calculation task dynamically
this.persistentWorker.register({
message: 'calculateTotal',
func: (numberList) => numberList.reduce((acc, curr) => acc + curr, 0)
})
Unregister Tasks
Remove unused tasks from the worker with the unregister() method, passing the task's message ID:
// Remove tasks no longer in use
this.persistentWorker.unregister('calculateTotal')
this.persistentWorker.unregister('processLargeDataset')