vue路由前进刷新、后退不刷新 keep-alive
2019-01-09 本文已影响74人
天字一等
转载自:https://segmentfault.com/a/1190000012083511
注意的地方:
在app.vue页面要
App.vue:
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view> <!--注意:需要缓存的页面 https://www.cnblogs.com/wangyunhui/p/8178392.html-->
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view> <!--特别注意,需要加上这行代码,这样的话不需要缓存才可以展示,我当时因为这点花了很多时间 -->
</div>
</template>
有时候需要根据路由跳转的路径来判断是否使用缓存,还是在当前页面重新调用接口加载数据,可以使用导航钩子beforeRouteEnter、beforeRouteLeave等等和location.reload(); 重新刷新页面来实现。
实例:
beforeRouteEnter是在进入页面的时候执行
beforeRouteEnter(to, from, next) { //beforeRouteEnter在mounted之前执行,进入页面的时候就会执行
//设置下一个路由的 meta
console.log(to)
var self = this;
if(from.path == '/userList'){
//to.meta.keepAlive = false; // B 跳转到 A 时,让 A 缓存,即不刷新(代码写在B页面)
//this.$router.go(0);
console.log(2)
//to.meta.keepAlive = false;
next(function () {
location.reload(); //next()和keep-alive组合,可以实现第二次进入页面的时候重新调用接口,而不是缓存
});
}else{
//to.meta.keepAlive = true;
next();
}
}