前沿
vite 页面引入worker
在src 新建一个 worker.d.ts 文件
declare module '*.worker.ts' { class WebpackWorker extends Worker { constructor(); } export default WebpackWorker; }
在 tsconfig.json 页面引入
"lib": ["esnext", "dom", "dom.iterable", "scripthost", "WebWorker"],
最后新建 work 文件夹
export {}; const getCounter = (params: any) => { console.log(params); const start = new Date().getTime(); console.log('开始计算斐波那契数任务'); let count = 0; // 1e9 const newArr = []; for (let i = 0; i < 1e9; i++) { count += i; } const end = new Date().getTime(); console.log('继续主线程,耗时:', end - start); postMessage(count); }; onmessage = function (event) { const { data } = event; const { type, params } = event.data; console.log(params); if (type === 'start') { getCounter(params); } if (data === 'stop') { postMessage('ended'); } console.log(event.data); };
最后在你需要的页面引入 头部(vue3 cli )
const worker = new Worker(new URL('@/workers/scan.worker.ts?worker', import.meta.url));
在vite 里面可以直接引入
import MyWorker from "@/utils/workers/workers.ts?worker"
下面的逻辑就是接受那边的数据
onMounted(() => { console.log(worker); worker.postMessage( { type: 'start', params: { name: 1 }, }); // set up an onmessage listener on Countdown worker object to listen to updates from the worker thread worker.onmessage = (e: any) => { console.log(e.data); // check if the counter value sent by the worker is divisible by 10, and if it is, call the getDogImage method again // if (counter.value % 10 === 0) { // getDogImage(); // } }; worker.onerror = (e: any) => { console.log(e); }; });
worker.onmessage 方法就是可以接受那边的处理完的数据 当然也可以不需要接受
缺点: 不能操作dom,
优点: 性能优化大大优化
标签:console,log,代码,worker,params,vue3,const,workers From: https://www.cnblogs.com/yf-html/p/18163717