背景
业务需求,实现跳转进页面的时候重新加载页面,后退的时候保持缓存。搜索了很多的回答,大概有几种方法:
1、keepalive判断router-view --> 缓存不生效。
2、includes --> 无法实现前进刷新
3、页面里做路由监听 --> 没有测试,太过于繁琐
方案
1、重写router的push和replace方法,记录路由的历史
2、跳转的方法里加入t参数,清除路由缓存,实现刷新
3、跳转回已有路由时,清除后面的记录,不会无限返回; exp a -> b -> c -> d, d跳转到b时,再返回时回到a
// App.vue
<keep-alive>
<router-view ref="routerView" :key="$route.fullPath"></router-view>
</keep-alive>
// router/index.js
Vue.use(VueRouter);
let historyList = [];
router.afterEach(to => {
if (!historyList.includes(to.path) && !to.query.replace) historyList.push(to.path);
});
// 监听返回事件
window.addEventListener('popstate', () => {
historyList.splice(1, historyList.length - 1);
});
function checkRoute(location) {
const index = historyList.findIndex(path => path === location.path);
if (index !== -1) {
const backLen = index + 1 - historyList.length;
historyList = historyList.slice(0, index);
router.go(backLen);
}
}
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
// 重写原型上的push和replace方法,统一处理跳转和错误捕获
VueRouter.prototype.push = function push(location) {
checkRoute(location);
location.query = Object.assign({}, location.query, {
t: new Date().getTime()
});
return originalPush.call(this, location).catch(err => console.log(err));
};
VueRouter.prototype.replace = function replace(location) {
checkRoute(location);
location.query = Object.assign({}, location.query, {
t: new Date().getTime(),
replace: true
});
return originalReplace.call(this, location).catch(err => console.log(err));
};
TIP
后续如果有问题继续更新。。。
网友评论