Skip to content
On this page

页面缓存 KeepAlive v1.1.0+

uni-simple-router 中,我们一直致力于提供更强大的路由解决方案。在之前的版本中,我们已经实现了嵌套路由的支持。然而,我们也意识到在 H5 平台上,缺乏 KeepAliveTransition 以及 RouterView 的解决方案,这可能限制了应用的最大化效益。

我们对此进行了深入的改进,并值得庆幸的是,在 v1.1.0 版本中,我们成功地弥补了这些不足。现在,用户可以在创建 RouterView 时传递插槽,以实现更灵活的配置,例如通过 Transition 包装或应用 KeepAlive,从而最大化提升应用的性能和用户体验。这一更新进一步增强了 uni-simple-router 的功能,使其更适用于各种场景。

陷阱提示

  1. KeepAliveTransition 仅支持H5,当你运行到其他端时请做好条件编译。
  2. RouterView 插槽仅支持 APPH5,其他端均不支持插槽。

基本使用

我们可以通过槽实现这种级别的控制:

vue
<simple-router-view v-slot="{ Component, route }">
  <component :is="Component"></component>
</simple-router-view>

如上代码,通过插槽(v-slot)的方式,我们实现了更高级别的控制。在上述代码中,我们利用 v-slot 获取了两个关键参数:Componentroute。通过使用 component 组件,我们进一步精细化了对组件的显示和渲染的控制。这种灵活性不仅仅限于组件的展示,还可以扩展到状态管理、权限控制、过渡效果等方面的自定义配置。

无匹配情况

当当前位置与 Router 注册的任何记录都不匹配时,matched 数组为空。默认情况下,如果没有提供槽,渲染内容将为空。通过提供一个槽,我们能够自行决定显示什么内容,不论是展示未找到的页面,还是采用默认行为。Component如果没有要渲染的组件,则为 null

vue
<simple-router-view v-slot="{ Component, route }">
  <component  v-if="route.matched.length > 0" :is="Component"></component>
  <div v-else>Not Found</div>
</simple-router-view>

v-slot 特性

提供两个回调参数:

  1. Component : 当前路由path匹配到的渲染组件,如果匹配失败则为 null
  2. route : 当前渲染组件对应的路由元信息,你可以在这里找到 详细

同时使用过渡及缓存

您还可以轻松地利用 TransitionKeepAlive 缓存页面,并添加过渡动画。实现这一步骤非常简单,只需按照以下几行代码即可:

xxx.vue

vue
<simple-router-view  v-slot="{ Component, route }">
  <transition :enter-active-class="`animate__animated ${route.meta.transition}`">
    <keep-alive>
      <component :is="Component"/>
    </keep-alive>
  </transition>
</simple-router-view>

routes.ts

ts
const router = createRouter({
  // .... 
  routes:[{
			path: `/issues_16/bug`,
			name: `issues_16bug`,
			component: __dynamicImportComponent__(`~@/examples/fixbug/issue_16/index.vue`, {
				pageType: `top`,
			}),
			children:[
				{
					path: `test1/:id`,
					name: `issues_16bug_test1`,
					component: __dynamicImportComponent__(`~@/examples/fixbug/issue_16/child/child1.vue`),
					meta:{
						transition:`animate__fadeInDown`
					}
				},
				{
					path: `test2`,
					name: `issues_16bug_test2`,
					component: __dynamicImportComponent__(`~@/examples/fixbug/issue_16/child/child2.vue`),
					meta:{
						transition:`animate__fadeInRight`
					}
				}
			]
		}]
})

非常简单,我这里在路由表中的meta下标记了一个transition,它的动画内容来自Animate.css。如果你喜欢,你也可以自己实现 Transition 组件的动画。

陷阱提示

  1. KeepAliveTransition 仅支持H5,当你运行到其他端时请做好条件编译。
  2. RouterView 插槽仅支持 APPH5,其他端均不支持插槽。
页面缓存 KeepAlive v1.1.0+ has loaded