Web Worker 简单使用
通信方法:
(1) 发送消息
主线程:worker.postMessage()
子线程:self.postMessage()
(2) 接收消息
主线程:worker.onmessage()
子线程:self.onmessage()
(3) 监听异常
主线程:worker.onerror()
子线程:self.onerror()
(4) 销毁方法
主线程:worker.terminate()
子线程:self.close()
(5) 加载脚本 (worker内部加载其他脚本)
importScripts('script1', 'script2')
// 主进程
<template>
<div class="menu-contain card">
<el-button type="primary" @click="handlerSendMsg">Send</el-button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const worker = ref()
worker.value = new Worker(new URL('@/workers/handlerArrWorker.ts', import.meta.url))
worker.value.onmessage = (res: any) => {
console.log(res, 'res')
}
const handlerSendMsg = () => {
worker.value.postMessage({msg: 'start'})
console.log(worker.value, 'worker.value')
}
</script>
<style scoped lang="scss">
</style>
// 子进程
self.onmessage = () => {
let list = []
for (let index = 0; index < 1000000; index++) {
list.push(Date.now())
}
self.postMessage(list)
}