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>
相关推荐
大橙子额17 分钟前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a2 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌412 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡3 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone3 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09013 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农3 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king4 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵5 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_5 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js