列表页缓存解决方案(keep-alive)Vue3.x

列表页缓存解决方案(keep-alive)Vue3.x

列表页切换详情,切回后要保持列表页切换前的状态是十分常见的需求,以下是我在项目中使用的处理方案,代码贴上,路过大佬望指教:

常规操作,router-view 上配置 keep-alive:

我将需要缓存的放到了vuex中

 <router-view v-slot="{ Component }" :key="key">
      <transition name="move" mode="out-in">
        <keep-alive :include="cachedViews">
          <component :is="Component" :key="route.path" />
        </keep-alive>
      </transition>
  </router-view>
const route, = useRoute()
const cachedViews = computed(() => {
  return store.state.cachedViews
})
return {
    route,
	cachedViews
}

在全局路由守卫中配置该页面是否需要缓存起来(这个项目中直接判断type = 1 的路由是侧边导航需要展示的为外页【列表页】):

router.beforeEach(async (to, from, next) => {
  // 只当前列表设置为缓存(大家按自己需求调整)
  if (from.meta.type === 1) {
    store.commit(SET_CACHEDVIEWS, [from.name])
  }
})

就是这么简单已经实现了跳转内页返回时,外页不会刷新

但是内页一般还有修改保存,点击了之后外面需要重新请求数据:

在api中直接配置,哪些请求完后缓存的页面需要重新请求

const productUserEdit = (data) => request({
  url: '/ProductUser/edit',
  method: 'post',
  data,
  catchViewReload: true
})
service.interceptors.request.use(config => {
	// ...
  if (config.catchViewReload) {
    store.commit(SET_CACHELOAD, true)
  }
  // ...
})

这样回到外页就知道需要重新请求数据了,使用自定义hooks封装起来:

useListLoad.js

import { onActivated, computed } from 'vue'
import { useStore } from 'vuex'
import { SET_CACHELOAD } from '@/store/mutation-type'

const useListLoad = (loadCb) => {
  const store = useStore()

  const isListLoad = computed(() => {
    return store.state.cachedLoad
  })
  onActivated(async () => {
    if (isListLoad.value) {
      await loadCb()
      store.commit(SET_CACHELOAD, true)
    }
  })
}

export default useListLoad

直接在需要的列表页引用:

import useListLoad from '@/hooks/useListLoad'
// ...
useListLoad(getListInit) // 传入列表请求方法

这个只适用于一次只需要缓存一个列表页的情况,有其他需要还需要另做其他实现

注:
需要缓存哪一个的页面,那个页面必须是直接被keep-alive所包裹的,并且必须设置key值,组件name值必须要与对应路由name值一模一样,否则不生效!

可以生效的情况:
在这里插入图片描述
不会生效的情况:
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值