一、前言
Vue3也已经推出很久了,Vue3更新的内容与原来Vue2的内容相比 还是有很多不同的地方的,其中路由缓存就是比较特殊的地方。
二、更新内容:
Vue2与Vue3的不同(直接上代码)
Vue2中
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<!-- vue2.中的配置 -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"/>
</template>
Vue3中
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<!-- vue3.中的配置 Component是固定写法 很多小伙伴没有搞明白-->
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" v-if="$route.meta.keepAlive"/>
</keep-alive>
<component :is="Component" v-if="!$route.meta.keepAlive"/>
</router-view>
</template>
router.js中的代码如下
{
path: '/',
name: 'Home',
component: Home,
meta:{
keepAlive: true
}
}
另外说明 Vue中有两个特殊的生命周期函数activated deactivated 只有在设置了路由缓存keepalive时才能生效,届时,activated的作用相当于created函数
动态设置keep-alive属性
// 使用组件内守卫,对离开页面事件做一些操作
// to为即将跳转的路由,from为上一个页面路由
// 可以在跳转路由时 对路由缓存进行更改或者设置
beforeRouteEnter(to, from, next) {
to.meta.keepAlive = true;
next();
// 路由继续跳转
}
批量设置路由缓存挑选
<router-view v-slot="{ Component }">
// 这里 include可以匹配正则表达式,或者组件的名称
// 在Vue3中 选项式组件比较适合,组合api中在script标签中设置name属性 前提是script标签内 一定要有内容
<keep-alive include="home,one,two">
<component :is="Component"/>
</keep-alive>
</router-view>
另外声明,如果你像要路由不仅在一级路由生效,还要在二级路由等等生效,只需要配置和一级路由相同的配置即可!!