vue组件动态缓存与动态刷新

发布时间 2023-06-27 21:17:38作者: Coderz1

动态缓存

前言

在项目中,为了减少性能消耗,有时我们需要使用keep-alive把组件缓存起来,但是并不是所有组件都需要被缓存,那么如何控制那些组件需要缓存呢?主要使用到路由meta,路由前置守卫,vux,动态组件。

实现

APP.vue

<script setup>
import { ref,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAlertsStore } from './store/modules/app.js'


const store = useAlertsStore()
const includes = computed(()=>{
  return store.$state.includes
})


const router = useRouter()
const tohome = ()=>{
  router.push('/home')
}

const totest = ()=>{
  router.push('/test')
}

</script>

<template>
  <div>
    <button @click="tohome">home</button>
    <button @click="totest">test</button>
    <router-view v-slot="{Component}">
      <keep-alive :include="includes">
        <component :is="Component"></component>
      </keep-alive>
    </router-view>
  </div>
</template>

<style>
.bg {
  background-color: pink;
}
</style>

路由index.js

import { createRouter, createWebHashHistory } from 'vue-router'
import { useAlertsStore } from '../store/modules/app.js'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    // 导入的.vue组件名必须和组件注册的名字一致 文件名最好全小写 组件首字母最好大写
    path: '/home',
    name: 'home',
    component: () => import('../views/home.vue'),
    meta: {
      name: 'home',
      keepAlive: true
    }
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('../views/testtwo.vue'),
    meta: {
      name: 'test',
      keepAlive: false
    }
  },
]


const router = createRouter({
  history: createWebHashHistory(),
  routes,
})


router.beforeEach((to, from, next) => {
  const store = useAlertsStore()
  if (to.meta.keepAlive && to.name) {
    store.setincludes({ name: to.name })
  }
  next() // 如果没传next 可以不用调用next函数 也能跳转
})



export default router

vuex

 state: () => {
    return {
      includes: [],
    }
  },
   actions: {
    // 添加需要缓存的组件
    setincludes(payload) {
      this.$state.includes = [...new Set([...this.$state.includes, payload.name])]
    },