Vue3后退不刷新,前进刷新

核心思想

  1. 使用keep-alive缓存页面信息
  2. 由于vue3中keep-alive只能通过组件名称缓存,每次都会动态创建一个新的组件包装下页面
  3. 每次路由前进时会根据路由的深度分配一个uuid并缓存,然后用此uuid创建一个动态组件包装页面
  4. 此方法可以解决a->b->a->c 然后后退 c->a->b->a的问题

PageKeepAlive组件源码

vue 复制代码
<template>
  <keep-alive :include="include">
    <component v-if="node" :is="node" :key="data.cid" />
  </keep-alive>
</template>
<script setup>
import { uuid } from '@/common/utils/StringUtil'
import { defineComponent, computed, reactive, nextTick } from 'vue'
import {useRouter} from 'vue-router'
const props = defineProps(['data'])

const router = useRouter()

const comp_cache = reactive({})
const position_cache = reactive({})

const include = computed(()=>{
  let target = []
  let expired = new Set(Object.keys(comp_cache))
  for (let cache of Object.values(position_cache)) {
    target.push(cache.cid)
    expired.delete(cache.cid)
  }
  nextTick(()=>{ // 删除过期的缓存
    for (let cid of expired) {
      delete comp_cache[cid]
    }
  })
  return target
})

const node = computed(()=>{
  let data = props.data
  if(!data || !data.cid || !data.comps) return null
  if (!comp_cache[data.cid]) {
    comp_cache[data.cid] = defineComponent({
      name: data.cid,
      setup() {
        return () => data.comps
      }
    })
  }
  return comp_cache[data.cid]
})

router.afterEach((to) => {
  let current = window.history.state.position
  let path = to.path
  for (let i of Object.keys(position_cache)) {
    let cache = position_cache[i]
    if (i > current) { // 大于当前位置的缓存清理掉
      delete position_cache[i]
    }
    if (i == current && cache.path != path) { // replace需要去掉缓存
      delete position_cache[i]
    }
  }
  let cache = position_cache[current]
  if (!cache) {
    position_cache[current] = cache = {
      cid: `comp_${uuid()}`,
      path
    }
  }
  to.meta.cid = cache.cid
})
</script>

使用方式

vue 复制代码
<router-view v-slot="{ Component, route  }">
	<PageKeepAlive :data="{cid: route.meta.cid, comps: Component}" />
</router-view>
相关推荐
阿珊和她的猫5 分钟前
React Hooks:革新组件开发的优势与实践
前端·react.js·状态模式
全栈技术负责人6 分钟前
AI时代前端工程师的转型之路
前端·人工智能
花归去24 分钟前
echarts 柱状图曲线图
开发语言·前端·javascript
喝拿铁写前端24 分钟前
当 AI 会写代码之后,我们应该怎么“管”它?
前端·人工智能
老前端的功夫27 分钟前
TypeScript 类型魔术:模板字面量类型的深层解密与工程实践
前端·javascript·ubuntu·架构·typescript·前端框架
Nan_Shu_6141 小时前
学习: Threejs (2)
前端·javascript·学习
G_G#1 小时前
纯前端js插件实现同一浏览器控制只允许打开一个标签,处理session变更问题
前端·javascript·浏览器标签页通信·只允许一个标签页
@大迁世界1 小时前
TypeScript 的本质并非类型,而是信任
开发语言·前端·javascript·typescript·ecmascript
GIS之路1 小时前
GDAL 实现矢量裁剪
前端·python·信息可视化
是一个Bug1 小时前
后端开发者视角的前端开发面试题清单(50道)
前端