当前位置: 首页 > 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(),
      };
    });

相关文章:

  • C语⾔数据类型和变量
  • charles 抓取https<仅web端>
  • c++ 预处理器和iostream 文件
  • 第十四届蓝桥杯:(二分算法)字串简写
  • ArcGIS操作:11 计算shp矢量面的质心坐标
  • 【朝夕教育】《鸿蒙原生应用开发从零基础到多实战》004-TypeScript 中的泛型
  • JavaScript 变量的使用
  • Windows 环境下 Nginx、PHP 与 ThinkPHP 开发环境搭建
  • 关于服务器cpu过高的问题排查
  • 软考网络安全工程师条件
  • 探秘基带算法:从原理到5G时代的通信变革【八】QAM 调制 / 解调
  • golang的io
  • NL2SQL-基于Dify+阿里通义千问大模型,实现自然语音自动生产SQL语句
  • C++初阶--基本语法讲解
  • 数据安全_笔记系列11:GDPR(通用数据保护条例)合规框架
  • CDefView::_OnFSNotify函数分析
  • STM32MP157A单片机移植Linux系统使用python链接云服务器
  • Spring统一格式返回
  • Spring学习笔记03——Spring Boot的文件结构
  • XGMII(10 Gigabit Media Independent Interface)详解
  • 滨海网站建设公司/公司网站如何建设
  • 新时代政府网站建设/世界网站排名查询
  • 成都模版网站制作/怎么找网站
  • 网站建设南通/站长工具免费
  • 网站设计要先做图么/百度经验怎么赚钱
  • 企业网站的缺点/搜狗搜索推广