当前位置: 首页 > article >正文

vue3缓存菜单

layout文件

<router-view v-slot="{ Component,route }">
            <transition name="el-fade-in-linear" mode="out-in">
              <keep-alive :include="include">
                 <component :is="formatComponentInstance(Component,route.path)" :key="route.path"/>
              </keep-alive>
            </transition>
          </router-view>



const menuTabStore = useMenuTabStore()
//缓存的组件数组 只能使用组件name
const include = computed(()=> menuTabStore.menuTabs.map(item => item.path))

//wrapperMap 缓存已经创建的组件包装器(wrapper)提高性能
let wrapperMap = new Map()
const formatComponentInstance = (component: any, path: string) => {
  let wrapper
  if (wrapperMap.has(path)) {
    wrapper = wrapperMap.get(path)
  } else {
    wrapper = {
      name: path, // 用path生成组件的name,
      render:()=> h(component)  // h的第一个参数可以是字符串,也可以是一个组件定义;h返回的是一个虚拟dom
    }
    wrapperMap.set(path, wrapper)
  }
  return h(wrapper)
}

pinan文件

import { ref } from 'vue'
import { defineStore } from 'pinia'
import router, { type Meta } from '@/router'

export interface MenuTabs {
  path: string
  meta: Meta
}

export const useMenuTabStore = defineStore(
  'menuTabStore',
  () => {
    // 菜单tabs
    const menuTabs = ref<MenuTabs[]>([])
    // 激活的tab
    const activate = ref('')

    function setMenuTabs(routes: MenuTabs[]) {
      menuTabs.value = routes
    }

    function pushMenuTab(route: any) {
        const routeCopy = {...route}
        if (!menuTabs.value.find((item) => item.path === routeCopy.path)) {
            menuTabs.value.push(routeCopy)
        }
        activate.value = route.path
    }

    function removeMenuTab(path: string) {
      const index = menuTabs.value.findIndex((item) => item.path === path)
      menuTabs.value = menuTabs.value.filter((item) => item.path !== path)
      if (activate.value === path) {
        const activateName = menuTabs.value[index]?.path || menuTabs.value[index - 1]?.path || ''
        setActivate(activateName)
      }
    }

    function setActivate(path: string) {
      if ((activate.value !== path ) && path) {
        router.push({ path })
      }
      activate.value = path
    }

    return {
      menuTabs,
      setMenuTabs,
      pushMenuTab,
      removeMenuTab,
      activate,
      setActivate
    }
  },
  {
    persist: true
  }
)


http://www.kler.cn/news/357789.html

相关文章:

  • Python从0到100(六十四):Python OpenCV-图像运算进阶实战
  • laravel-数据库查询
  • HarmonyNext保存Base64文件到Download下
  • 使用多路复用技术提升网站性能
  • 页面中包含多个el-popover,点击其中一个显示,其他的关闭(多个el-popover,click触发,点击都不消失的问题)
  • docker 基础镜像里 scratch 和alpine,ubuntu centos详细对比(镜像优化)
  • 如何声明一个类?类如何继承?
  • 网络最快的速度光速,因此‘‘光网络‘‘由此产生
  • Codeforces Round 979 (Div. 2) B. Minimise Oneness
  • WileyNJDv5_Template模板无法编译生成pdf文件
  • HTML+CSS (基础)
  • qt 序列化和反序列化
  • AI 代写是变现最快的副业项目,没有之一
  • docker harbor
  • Python学习的自我理解和想法(16)
  • 简单说说 spring构造器循环依赖 为什么无法解决(源码解析)
  • webpack 学习入门
  • Spring Boot技术:图书进销存管理的创新实践
  • AI金融攻防赛:YOLO理论学习及赛题进阶思路(DataWhale组队学习)
  • 【算法】C++中的二分查找