在worker就绪后挂载vue



我使用msw.js作为请求模拟库。

然而,在msw web worker准备好之前,一些请求在开发时被触发。我可以肯定,因为第一个请求失败了。我用DevTools在UI中重试它们,它像预期的那样工作。

Here mymain.ts:

import { createApp } from 'vue'
import { router } from './routes'
import { pinia } from './pinia.setup'
import App from './App.vue'
import { onUnhandledRequest } from './mocks/browser'
const prepareWorkers = async () => {
if (process.env.NODE_ENV === 'development') {
const { worker } = await import('./mocks/browser')
await worker.start({
onUnhandledRequest
})
}
return Promise.resolve()
}
prepareWorkers().then(() => {
const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')
})

正如您所看到的,我已经按照不同的安装建议执行了,但没有成功,我已经没有主意了。

我正在使用vite,它也可能是与它相关的东西,因为所有文件都是从vite开发服务器下载的。此外,请求是在函数外部的可组合中触发的。为例:

// useMyStatefulComposable.ts
// instantiate it once for multiple composable instances
const allResquests = Promise.allSettled(urls.map(url => fetch(u)))
export const useMyStatefulComposable = () => {
// using the allRequests result inside the composable
return { myReactiveData }
}

请求立即在useMyStatefulComposable中完成。没有等待应用程序初始化的Ts是一个需要修复的错误。如果它们应该被执行一次,则需要惰性地执行:

let allRequests;
export const useMyStatefulComposable = () => {
if (!allRequests) {
allRequests = Promise.allSettled(urls.map(url => fetch(u)))
}
...
return { myReactiveData }
}

考虑到这些是allRequests的结果,需要在useMyStatefulComposable中处理,承诺可能也需要在if (!allRequests)中链接。

最新更新