1.用history模式。(可以在不刷新页面的情况下更新 URL)(需要在创建 Router 实例时进行配置)
该模式下,浏览器会自动监听url的值,如果发送变化会自动发送请求。服务器端通常需要配置一个"后备"路由,将所有未匹配的 URL 都指向应用程序的入口点(通常是 index.html)。
2.加<keep-alive>包裹实现缓存。
注意如果路由组件有嵌套路由,需要在嵌套的路由组件也使用 keep-alive
进行缓存。
const routes = [
{
path: '/user',
component: UserLayout,
children: [
{
path: '',
component: UserList
},
{
path: 'profile',
component: UserProfile
},
{
path: 'settings',
component: UserSettings
}
]
}
]//嵌套路由示例
下面是一个使用 keep-alive 的嵌套路由示例:
<template>
<div id="app">
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
在这个例子中,我们将整个 router-view 组件包裹在 keep-alive 中。这样,所有被渲染的组件都会被缓存下来。(这个栗子可以实现动态缓存组件。因为通过具名插槽来获取当前router-view中要渲染的组件,随后又在里面用keep-alive 来包裹这个要显示的组件。所以每当router-view切换里面的组件时,就会被keep-alive 包裹。实现动态缓存组件的功能。)
如果我们只想缓存某些特定的组件,可以使用 keep-alive 的 include 或 exclude 属性:
<keep-alive include="UserList,UserProfile">
<router-view />
</keep-alive>
3.保存路由状态
组件卸载时保存路由状态,在组件重新挂载时恢复状态。可以使用 Pinia或者其他状态管理工具来实现这一功能。
// store/routeStore.js
import { defineStore } from 'pinia'
export const useRouteStore = defineStore('route', {
state: () => ({
routeState: null
}),
actions: {
saveRouteState() {
this.routeState = { ...this.$route }
},
restoreRouteState() {
if (this.routeState) {
this.$router.push(this.routeState)
}
}
}
})
在组件中使用:
<script setup>
import { useRouteStore } from '@/store/routeStore'
const routeStore = useRouteStore()
onCreated() {
routeStore.saveRouteState()//创建时,调用函数,存入初始的路由状态到pinia里
}
onBeforeUnmount() {
routeStore.saveRouteState()//销毁前,调用函数,将目前对应的路由状态存入pinia里
}
onMounted() {
routeStore.restoreRouteState()//渲染时,调用函数,获取之前的路由状态,并push到(它)
}
</script>
在这个实现中,我们使用 Pinia 创建了一个名为 useRouteStore 的 store,其中包含了保存和恢复路由状态的相关逻辑。