1、具体的worker文件
//search.worker.js
/** 监听主线程发送的消息*/
self.onmessage = (messageEvent) => {
...
...
//把处理后的结果返回
this.postMessage(**);
};
2、包装worker相应的逻辑
//search.js
import workerCode from './search.worker.js?raw';//?raw是为了标识以文件的方式import,而不是以内容
const blob = new Blob([workerCode], { type: 'application/javascript' });
const workUrl = window.URL.createObjectURL(blob);
let worker = null;
export const searchFn = (options) => {
return new Promise((resolve, reject) => {
worker = new Worker(workUrl);
// 通过通道传数据
worker.postMessage(JSON.stringify(options));
worker.onmessage = (e) => {
// 获取到的搜索结果
let _data = e.data && JSON.parse(e.data);
resolve(_data);
};
});
};
3、在vue文件中使用时
//index.vue
import { searchFn } from './search.js';
searchFn(**).then(res=>{
//获取到的结果
}
).catch(err=>{
}
)
4、扩展
①、关于window.URL.createObjectURL,可以参考文章