vue3 setup语法糖使用keep-alive

给对应的路由添加元信息是否缓存

meta: { title: '缓存页面', keepAlive: true }

设置keep-alive的页面添加拦截判断,这里使用了include方法

<router-view #default="{ Component }" v-if="routerViewShow">
    <transition appear name="fade-transform" mode="out-in">
        <keep-alive :include="includeList">
            <component :is="Component" />
        </keep-alive>
    </transition>
</router-view>

监听路由变化判断改路由是否缓存

import { router } from '@/router'
import { watch } from 'vue'
  
const includeList:any = []
watch(() => router.currentRoute.value,(val) => {
  if (val.meta.keepAlive && includeList.indexOf(val.name) === -1) {
    includeList.push(val.name)  
  }
},{immediate: true,deep: true})

注意!!!因为使用了setup语法糖,所有得安装一个插件

npm i vite-plugin-vue-setup-extend
yarn add vite-plugin-vue-setup-extend

在vite.config文件安装插件

import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
export default defineConfig({
  plugins: [ VueSetupExtend() ]
})

需要在页面的script标签添加name

<script lang="ts" setup name="name"></script>

你可能感兴趣的:(vue.js,javascript,前端)