前言
项目中经常遇到些奇怪的问题,这里做一些记录,方便后续快速查看定位。不同的版本之间,写法也都不一样。
正文记录
1、vue-router路由守卫跳转next()报错
router.beforeEach(async (to, from, next) => {
const token = sessionStorage.getItem("token");
if (token) {
next();
} else {
if (whiteList.indexOf(to.path) !== -1) {
next();
} else {
if (to.query.thing) {
doSomething(to.query.thing).then(res=>{
if (res.code == 0) {
sessionStorage.setItem("token", res.data.access_token);
next("/home");
} else {
next("/login");
}
})
} else {
next("/login");
}
}
}
});
注意:在vue-router@3.x里面这么写是没有任何问题的,功能也正常,但是在vue-router@4.x里面会报错 Invalid navigation guard,无法跳转,根本原因是不能用 then 的方式,要用async/await的方式去做。
router.beforeEach(async (to, from, next) => {
const token = sessionStorage.getItem("token");
if (token) {
next();
} else {
if (whiteList.indexOf(to.path) !== -1) {
next();
} else {
if (to.query.thing) {
let res = await doSomething(to.query.thing);
if (res.code == 0) {
sessionStorage.setItem("token", res.data.access_token);
next("/home");
} else {
next("/login");
}
} else {
next("/login");
}
}
}
});
2、开发环境配置代理
proxy: {
"/api": {
target: "http://x.x.x",
changeOrigin: true,
rewrite: (path) => {
return path.replace(/^\/api/, "");
},
},
},
以上是vite@3.x的代理配置写法。
proxy: {
"/api": {
target: "http://x.x.x",
changeOrigin: true,
pathRewrite: {
"^/api": "/api",
},
},
},
这是webpack的写法,两者重点在于重新路径的地方有所不同,差之毫厘,谬之千里!
后记
持续更新!