vue3 实现路由缓存

<template>
    <nav>
        <router-link to="/" @click="updateComponent">Home</router-link> |
        <router-link to="/about" @click="updateComponent">About</router-link>
    </nav>
    <router-view v-slot="{ Component }">
        <keep-alive include="home,about">
            <component :is="Component" :key="$route.path" />
        </keep-alive>
    </router-view>
</template>

<script setup lang="ts"></script>
<template>
    <div class="about">
        <p>{{ a }}</p>
        <el-button type="primary" @click="derr">Primary</el-button>
    </div>
</template>

<script setup lang="ts">
import { ref, defineOptions, onActivated, onDeactivated } from "vue";

defineOptions({
    name: "about",
});
let a = ref(0);
const derr = () => {
    a.value = a.value + 1;
};
onActivated(() => {
    console.log("Component activated");
});

onDeactivated(() => {
    console.log("Component deactivated");
});
</script>
<template>
    <div class="home">
        <img alt="Vue logo" src="../assets/logo.png" />
    </div>
</template>

<script setup lang="ts">
import { defineOptions } from "vue";
defineOptions({
    name: "home",
});
</script>
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'


const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import(/* webpackChunkName: "about" */ '../views/HomeView.vue'),
    meta: {
       
      keepAlive: true 
    }
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    meta: {
       
      keepAlive: true 
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值