zoukankan      html  css  js  c++  java
  • vue利用keep-alive / beforeRouteLeave 前进刷新后退不刷新 ,亲测可用。

    在vue中默认router-link进入页面组件都是不缓存的。对于数据不会更新的页面。可以使用keep-alive来缓存以提高性能。
    在项目src/router/index.js中。对于需要缓存的路由加meta中加上keepAlive: true
    复制代码
    1 export default new Router({
    2   routes: [
    3     {path: '/',
    4       redirect: '/Home',
    5       meta: {keepAlive: true,}
    6     },
    7 ]
    8 })
    复制代码

    在app.vue中

    复制代码
    1 把
    2 <router-view></router-view>
    3 改为
    4 <keep-alive>
    5       <router-view v-if="$route.meta.keepAlive"></router-view>
    6 </keep-alive>
    7 <router-view v-if="!$route.meta.keepAlive"></router-view>
    8     
    复制代码


    利用beforeRouteLeave动态决定要不要缓存刷新。

    要求:

    首页Home-列表页List-详情页Detail。前进刷新,后退不刷新,且还在原来的滚动位置。

    即除了在详情页退到列表页不刷新外,其他方式(搜索、分类、推荐等)进入列表都刷新。

    在router/index.js中,Llist路由加上keepAlive: true, 

     
    复制代码
    {
          path: '/list/:categoryId?/',
          name: 'List',
          component: List,
          meta: {
            keepAlive: true, 
    },
    {
          path: '/detail/:goodsId',
          name: 'Detail',
          component: Detail
    }
    复制代码
    在vue中 
     beforeRouteLeave (to, from, next) { }
     表示在路由页面离开时执行。
    其中to表示下一个要进入的路由。form表示当前页面路由。next()表示执行跳转。
    我们只需要在函数中判断,只要下一级是Detail则把List的keepAlive设为true,其他设为false即可。
    复制代码
    beforeRouteLeave(to, from, next) {
            console.log('beforeRouteLeave  to.path='+to.path + ' from.path='+from.path);
            if(to.path.indexOf('/dataAssets/maintain/edit/') > -1 || to.path.indexOf('/dataAssets/maintain/details/') > -1 ){
                this.$route.meta.isBack = true;
            }else{
                this.$route.meta.isBack = false;
            }
            next()
        },
        
        activated() {
            console.log('activated this.$route.meta='+ JSON.stringify( this.$route.meta) )
            if(!this.$route.meta.isBack){
                this.pageConfig.currentPage = 1;
            }
            this.getList(this.pageConfig.currentPage);
            
        },
    复制代码
     
     
     
     
    根据 this.$route.meta.isBack 来判断是不是返回的状态,如果是,就缓存页码,如果不是,就请求第一页。
  • 相关阅读:
    创建大顶堆
    大顶堆的实现
    二叉树的前序,中序,后序,层序实现
    链表实现多项式相加
    225. Implement Stack using Queues
    232. Implement Queue using Stacks
    JavaScript 实现队列操作
    Vue 路由守卫
    回文数 & {}[]() 符号判断

  • 原文地址:https://www.cnblogs.com/yuer01/p/14267944.html
Copyright © 2011-2022 走看看