我已经尝试通过 vue plugin 在 web worker 中使用 axios 请求
我的代码如下所示:
//worker.js
import axios from 'axios';
export default function getApiData (args) {
axios.get('/api/test').then(response => {
console.log(response);
});
}
和 Vue 的主文件
//main.js
import getApiData from './worker.js';
Vue.use(VueWorker);
window.vueApp = new Vue({
//...
created: function () {
this.updateWorker = this.$worker.create([
{
message: 'getApiData ',
func: getApiData
}
]);
this.testWorker.postMessage('getApiData ', [this.args])
.then(result => {
console.log(result);
})
},
//...
}
我得到了这个错误
Uncaught ReferenceError: axios__WEBPACK_IMPORTED_MODULE_0___default is not defined
我做错了什么?
最佳答案
我遇到了同样的问题,并通过回到基础来解决它 - 使用普通的旧 XMLRequest(见下文)。
您不能在 worker 内部使用 axios,因为在后台创建的 blob 用于加载 worker.js
在与您的 main.js
不同的上下文中运行.为了让 axios 工作,你必须设置一个新的 webpack bundler 来单独捆绑 worker。我不想这样做 - 它使项目结构变得不必要复杂。
这是一个简单的解决方案(适用于 json 和非 json 响应)。
// worker.js
export default () => {
self.addEventListener('message', e => {
if (!e) return;
// wrap in try/catch if you want to support IE11 and older browsers
// that don't support Promises. The implementation below doesn't work
// even when polyfills are loaded in the main project because
// the worker runs in a different context, ie no webpack bundles here.
try {
const fetchData = (url, isJSON = true) => {
return new Promise((resolve, reject) => {
function reqListener() {
if (this.status !== 200) {
return reject();
}
const response = isJSON
? JSON.parse(this.responseText)
: this.responseText;
resolve(response);
}
const oReq = new XMLHttpRequest();
oReq.addEventListener('load', reqListener);
oReq.open('GET', url);
oReq.send();
});
};
const baseUrl = 'https://static.newsfilter.io/';
const { articleId } = e.data;
const jsonUrl = baseUrl + articleId + '.json';
const htmlUrl = baseUrl + articleId + '.html';
// My use case requires 2 requests in parallel.
const tasks = [fetchData(jsonUrl), fetchData(htmlUrl, false)];
Promise.all(tasks)
.then(data => {
postMessage({ json: data[0], html: data[1] });
})
.catch(error => {
postMessage({ isError: true, error });
});
} catch (error) {
postMessage({ isError: true });
}
});
};
关于vue.js - 如何在带有 vue 的 web worker 中使用 axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828368/