菜鸟记---vue--route返回之页面刷新与不刷新问题

7,147 阅读1分钟

1:刷新--正常写返回就是刷新的

{ path: '', name: '', component: (resolve) => require([''], resolve), } 2:不刷新---在配置路由的时候, 给不刷新的页面配置一个参数, 这样这个页面就不会刷新了
{
    path: '',
    name: '',
    component: (resolve) => require([''], resolve), 
    meta: {
        keepAlive: true ,// 需要被缓存
    },
}

3:刷新不刷新都存在 B-->A的时候不刷新和 C-->A刷新(字母均为路由名字)

<!--route文件-->
{
    path: '',
    name: '',
    component: (resolve) => require([''], resolve), 
    meta: {
        keepAlive: true ,// 需要被缓存
        isBack:false, //用于判断上一个页面是哪个
    },
}
<!--vue文件-->
data(){
    return{
        isFirstEnter: true,//判断是否第一次进入页面   存在浏览器刷新的情况
    }
},
created(){
    this.isFirstEnter = true;
},
activated() {
    if(this.$route.meta.isBack || this.isFirstEnter){
        this.getList(this.params);
    }
    //还原到原始状态 避免一直是ture影响其余页面缓存
     this.$route.meta.isBack = false       
     this.isFirstEnter = false;
},
beforeRouteEnter(to, from, next){
    if(from.name == 'C'){
        to.meta.isBack = true;        
    }
    next();
},

更新一个新发现

BC页面返回A的姿势 如:

B: A页面刷新 滚动条回到顶部

this.$router.push({
  name: "",
  params: { }
});

C: A页面刷新 且滚动条定位到之前浏览的位置

this.$router.go(-1)

采用this.$router.push方式返回到页面, 并且 要缓存定位呢?采用这个方式返回是拿不到meta里面的参数

beforeRouteLeave(to, from, next){
    if(to.name == '#qqq'){
         let position = document.documentElement.scrollTop;
         setCookie('SAVE_POSITION', position,1) //离开路由时把位置存起来
    };
    if(to.name == 'wwww'){
        setCookie('SAVE_POSITION', 0,1) //去w'w'w时把数据清空,以免影响了其余的页面的效果
    };   
    next();
},
watch:{
    '$route' (to, from) {
        if(from.name == 'wwww'){
            this.getList(this.params);
        }else{
            this.$nextTick(function(){
                let position = getCookie('SAVE_POSITION') //返回页面取出来
                window.scroll(0, position)
            });
        }
    }
}

当然如果不是自己写的返回按钮 使用的浏览器的返回按钮 还有一个方法, 在路由配置项里配置这个方法

mode:'history',
scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
        return savedPosition
    } else {
        return { x: 0, y: 0 }
    }
},

知识点: 钩子函数的执行顺序

不使用keep-alive beforeRouteEnter --> created --> mounted --> destroyed

使用keep-alive beforeRouteEnter --> created --> mounted --> activated --> deactivated

再次进入缓存的页面,只会触发beforeRouteEnter -->activated --> deactivated 。

created和mounted不会再执行。

我们可以利用不同的钩子函数,做不同的事。

务必理解上述钩子函数的执行时机和执行顺序,本教程的核心就依赖于此钩子函数

activated和deactivated是使用keep-alive后,vue中比较重要的两个钩子函数,建议详细了解下。