当前位置: 首页 > news >正文

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(),};});

http://www.lryc.cn/news/546283.html

相关文章:

  • 校园快递助手小程序毕业系统设计
  • python量化交易——金融数据管理最佳实践——使用qteasy管理本地数据源
  • BIO、NIO、AIO、Netty从简单理解到使用
  • 计算机毕业设计SpringBoot+Vue.js工厂车间管理系统源码+文档+PPT+讲解)
  • 一、图形图像的基本概念
  • 前端跨域问题初探:理解跨域及其解决方案概览
  • SQL分组问题
  • Oracle 数据库基础入门(二):深入理解表的约束
  • DeepSeek掘金——DeepSeek-R1驱动的房地产AI代理
  • WebP2P技术在嵌入式设备中的应用:EasyRTC音视频通话SDK如何实现高效通信?
  • 【零基础到精通Java合集】第三集:流程控制与数组
  • VsCode + EIDE + OpenOCD + STM32(野火DAP) 开发环境配置
  • 【vue-echarts】——01.认识echarts
  • 【http://noi.openjudge.cn/】4.3算法之图论——1538:Gopher II
  • Linux常见操作命令
  • Linux下测试Wifi性能——2.Linux下wifi指令
  • (十 九)趣学设计模式 之 中介者模式!
  • Leetcode 54: 螺旋矩阵
  • abseil-cpp:环境搭建
  • Centos7部署k8s(单master节点安装)
  • RPA 职业前景:个人职场发展的 “新机遇”
  • 详解DeepSeek模型底层原理及和ChatGPT区别点
  • 《2025年软件测试工程师面试》JAVA基础面试题
  • 【算法学习之路】5.贪心算法
  • 如何打造一个安全稳定的海外社媒账号?
  • 【Python 数据结构 5.栈】
  • Qt开发⑪Qt网络+Qt音视频_使用实操
  • JavaEE--计算机是如何工作的
  • API接口:企业名称、注册号、统一社会信用代码、企业类型、成立日期和法定代表人等数据 API 接口使用指南
  • 微信小程序text组件decode属性的小问题