feat: 换更合理的方式

This commit is contained in:
wanchun 2023-03-29 16:35:42 +08:00
parent 9641b0dc67
commit 0eb8d88472

View File

@ -39,7 +39,9 @@ export const createRouter = (routes) => {
let isInit = false let isInit = false
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
if(!isInit) { if(isInit){
return next()
}
isInit = true isInit = true
const beforeRenderConfig = plugin.applyPlugins({ const beforeRenderConfig = plugin.applyPlugins({
key: "beforeRender", key: "beforeRender",
@ -49,7 +51,9 @@ export const createRouter = (routes) => {
action: null action: null
}, },
}); });
if (typeof beforeRenderConfig.action === "function") { if (typeof beforeRenderConfig.action !== "function") {
return next();
}
const rootElement = document.createElement('div'); const rootElement = document.createElement('div');
document.body.appendChild(rootElement) document.body.appendChild(rootElement)
const app = createApp(beforeRenderConfig.loading); const app = createApp(beforeRenderConfig.loading);
@ -57,19 +61,15 @@ export const createRouter = (routes) => {
try { try {
const initialState = await beforeRenderConfig.action({router, history}); const initialState = await beforeRenderConfig.action({router, history});
updateInitialState(initialState || {}) updateInitialState(initialState || {})
next();
} catch(e){ } catch(e){
next(false);
console.error(`[fes] beforeRender执行出现异常`); console.error(`[fes] beforeRender执行出现异常`);
console.error(e); console.error(e);
} }
app.unmount(); app.unmount();
app._container.innerHTML = ''; app._container.innerHTML = '';
document.body.removeChild(rootElement); document.body.removeChild(rootElement);
}
}
// 避免在beforeRender action中操作路由或者location.href构建后会出现卡死
setTimeout(() => {
next();
}, 0);
}) })
plugin.applyPlugins({ plugin.applyPlugins({