1题暖、具體的worker文件
//search.worker.js
/** 監(jiān)聽主線程發(fā)送的消息*/
self.onmessage = (messageEvent) => {
...
...
//把處理后的結(jié)果返回
this.postMessage(**);
};
2单刁、包裝worker相應(yīng)的邏輯
//search.js
import workerCode from './search.worker.js?raw';//?raw是為了標(biāo)識以文件的方式import,而不是以內(nèi)容
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);
// 通過通道傳數(shù)據(jù)
worker.postMessage(JSON.stringify(options));
worker.onmessage = (e) => {
// 獲取到的搜索結(jié)果
let _data = e.data && JSON.parse(e.data);
resolve(_data);
};
});
};
3、在vue文件中使用時
//index.vue
import { searchFn } from './search.js';
searchFn(**).then(res=>{
//獲取到的結(jié)果
}
).catch(err=>{
}
)
4猜拾、擴(kuò)展
①即舌、關(guān)于window.URL.createObjectURL,可以參考文章