vite-vue3使用web-worker应用指南和报错解决
主线程:初始化worker和监听子线程的消息
let worker: any;
const salesConfigData = ref<any[]>([]);
// 显示非上架
const showNotList = ref(false);
// /src/views/ceshi/salesConfig/worker.js
worker = new Worker(new URL("/src/views/ceshi/salesConfig/components/worker.js", import.meta.url), {
type: "module",
});
worker.onmessage = (e) => {
console.log(777777887, e);
salesConfigData.value = e.data;
};
主线程:主动触发消息
watch(
[() => props.salesConfigFeatrues, () => props.saleProductsOptions, showNotList],
([features, products, showNotListVal]) => {
const filteredProducts = products.filter((p) => props.salesModel.includes(p.value));
const rawData = features.map((feature) => {
const rawFeature = toRaw(feature);
return {
...rawFeature,
salesProducts: toRaw(rawFeature.salesProducts).slice(),
};
});
console.log(777777880, features, products, rawData);
worker.postMessage({
features: rawData,
products: filteredProducts,
showNotList: showNotListVal,
});
},
{ immediate: true }
);
子线程:worker线程接受参数,处理数据,发消息
import { formatsalesConfigFeatrues } from "@/views/ceshi/salesConfig/utils";
self.onmessage = function (e) {
console.log(777777881, e);
const { features, products, showNotList } = e.data;
const result = formatsalesConfigFeatrues(features, products, showNotList);
self.postMessage(result);
};
// self.addEventListener(
// "message",
// function (e) {
// console.log(777777882, e);
// self.postMessage("You said: " + e.data);
// },
// false
// );
经典错误1: [plugin:vite:worker-import-meta-url] Expression expected
解决办法:确保路径参数正确
worker = new Worker(new URL("/src/views/ceshi/salesConfig/components/worker.js", import.meta.url), {
type: "module",
});
经典错误2: DataCloneError: Failed to execute 'postMessage' on 'Worker': [object Array] could not be cloned. at watch.immediate
解决办法:传输的数据中存在proxy数组或者function等无法被拷贝的类型,这里处理数组:
const rawData = features.map((feature) => {
const rawFeature = toRaw(feature);
return {
...rawFeature,
salesProducts: toRaw(rawFeature.salesProducts).slice(),
};
});