用 vue 做了一个保存页面历史记录的功能,测试环境 npm run dev好使,npm run build到生产环境就不生效了
router.afterEach((to) => {
if (typeof window !== "undefined") {
localStorage.setItem('to.path', to.fullPath);
}
});
router.beforeEach((to, from, next) => {
if (typeof window !== "undefined") {
const topath = localStorage.getItem('to.path');
if (to.fullPath === '/' && from.fullPath === '/' && topath) {
router.push(topath);
}
}
next();
});
报错:Hydration completed but contains mismatches
并且页面显示内容错乱:标题是第二页,内容是首页。
猜测到是因为router.push重新跳转的问题,但不知道怎么修改,最后测试改成下面这样好使。
router.afterEach((to, from) => {
if (typeof window !== "undefined") {
const topath = localStorage.getItem('to.path');
if (to.fullPath === '/' && from.fullPath === '/' && topath && topath !== '/') {
router.push({path: topath});
} else {
localStorage.setItem('to.path', to.fullPath);
}
}
});
topath !== '/' 是为了避免死循环。问题解决。