一、创建worker.js文件,引入使用
console.log('Worker loaded and running!');
let hand = 'left'
self.addEventListener('message', function (event) {
const data = event.data;
if (data.type === 'initialize') {
hand = data.hand
} else if (data.type === 'FS_DATA') {
const keysToExtract = ['FS4', 'FS5', 'FS6'];
const newData = {};
keysToExtract.forEach((key, index) => {
if (data.data[key]) {
const fs = (hand !== 'left') ? `FS${index + 4}` : `FS${index + 1}`;
newData[key] = data[key];
const result = {
id: `mychart${index + 1}`,
data: data.data[key],
fs: fs,
type: 1,
};
self.postMessage(result);
}
});
}
}, false);
function parseData(arrBytes) {
var str = '';
for (var i = 0; i < arrBytes.length; i++) {
var tmp;
var num = arrBytes[i];
if (num < 0) {
tmp = (255 + num + 1).toString(16);
} else {
tmp = num.toString(16);
}
if (tmp.length == 1) {
tmp = '0' + tmp;
}
str += tmp;
}
return str;
}
function parseUint8Array(data) {
const decoder = new TextDecoder('utf-8');
const text = decoder.decode(data);
self.postMessage(text);
return text
// 这里可以做进一步处理
}
function parseUint8ArrayA(data) {
const decoder = new TextDecoder('utf-8');
const instruct = decoder.decode(data);
console.log('接收z指令', text);
const result = {
type: 2,
text: instruct
};
self.postMessage(result);
// 这里可以做进一步处理
}
import MyWorker from './worker?worker';
使用 postMessage方法导出处理好的数据
二、在mounted或者onLoad监听addEventListener方法,接收处理后的数据
this.worker = new MyWorker();
this.worker.addEventListener(
'message',
function (event) {
const result = event.data;
if (result.type == 1) {
const { id, data, fs } = result;
this.updateChart(id, data, fs);
}
}.bind(this)
);
三、postMessage方法传入需要处理的数据
this.worker.postMessage(data);
四、销毁前终止Worker
if (this.worker) {
this.worker.terminate(); // 组件销毁前终止Worker
}
使用后效果是有的但是不多