Vue页面缓存:控制页面刷新/不刷新

5,463 阅读1分钟
一、问题提出的背景

某天开会的时候,运营童鞋使用使用后台系统时提出了这样一个问题:刚查好的学员列表,点进去详情页看了一眼数据,返回列表后数据已经被刷新,又要重新查询一遍,有什么办法能返回的时候保留上一次查询的数据吗?

二、问题解决方案

经查阅资料,vue提供了keep-alive缓存机制。 详情参考vue官方文档

1.在vuex中存储一个keepAlive数组,保存那些需要被缓存的页面:代码如下:

<template>
    <transition>
        <keep-alive :include="keepAlive" :max="6">
            <router-view/>
        </keep-alive>
    </transition>
</template>

<script>
    import { mapState } from 'vuex'
    export default {
        data(){
            return{

            }
        },
        computed: {
            ...mapState('state', {
                keepAlive: state => state.page.keepAlive,
            })
        },
        created() {
            //console.log('a:',this.keepAlive)
        }
    }
</script>

2.在需要缓存的页面路由meta增加cache参数:

{
    path: 'orderMg',
    name: `orderMg`,
    meta: { title: '学费缴费订单', icon: 'file-powerpoint', cache: true},
    component: () => import('@/module/order/pages/orderMg/orderMg.vue'),
},

3.全局路由钩子beforeRouteLeave中获取cache参数,进行store缓存

// 页面是否需要缓存的逻辑代码
Vue.mixin({
    async beforeRouteLeave(to, from, next) { // 路由离开前的钩子
        if (from.meta.cache) { // 如果要离开的路由有cache这个属性,则触发vuex把该路由的名字储存起来
            await store.dispatch('state/page/saveCache',from.name)
        }
        if (to.params.noCache === 'true' || to.params.noCache === true) { // 如果要去到的路由不需要缓存, 则触发vuex把该路由的名字删除
            await store.dispatch('state/page/removeCache',to.name)
        }
        // 加await是为了确保在调用next去到下个页面之前, 储存/删除的操作一定先完成。
        next()
    }
})

4.已经缓存的页面如需要刷新,即移除缓存,在跳转该页面前附带路由参数:

this.$router.push({name: 'coachMg', params:{noCache:true}})

noCache为true时就会触发beforeRouteLeave中store进行removeCache操作,这样就可以控制一个列表页新增数据返回该页面时noCache为true刷新页面,详情页面返回时noCache为false继续保持缓存该页面不刷新。