主题
预加载路由组件 v1.1.6+
在过去的版本中,uni-simple-router
虽然提供了按需加载组件的功能,但随着项目规模的不断扩大,路由组件的体积也随之增加。这种情况导致在页面跳转时,需要花费大量时间下载和加载相关组件,进而影响用户的使用体验。
为了应对这一问题,我们很高兴地宣布,在新版本中引入了预加载组件的功能。该功能能够提前加载需要的组件,从而减少页面跳转时的等待时间。这不仅解决了过去版本中由于按需加载组件而导致的加载延迟问题,还显著提升了整体的用户体验。
陷阱提示
当前功能仅为H5
提供,当你运行到其他端时请做好条件编译。
基本使用
要想预加载一个路由组件,我们需要先为这个路由组件设置一个 name
,假设我们的路由表为如下结构:
ts
import { __dynamicImportComponent__ } from '@/uni-simple-router' export const customTabbar=[{ path:`/customTabbar`, name:`customTabbar`, component:__dynamicImportComponent__(`../../examples/tabbar/index.vue`,{ pageType: `top`, }), children:[ { path:`home`, name:`customTabbarHome`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/home.vue`), children:[ { path:`child/:id(\\d{3})`, name:`customTabbarHomeChild`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/children/commonChild.vue`) } ], }, { path:`class`, name:`customTabbarClass`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/class.vue`), }, { path:`release`, name:`customTabbarRelease`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/release.vue`), }, { path:`news`, name:`customTabbarNews`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/news.vue`), }, { path:`me`, name:`customTabbarMe`, component:__dynamicImportComponent__(`~@/examples/tabbar/children/me.vue`), }, ] } ]
我们现在需要加载 name
为 customTabbarHomeChild
的路由组件:
ts
import { createRouter, preloadRoutes } from '@/uni-simple-router' // 记得换成自己的路径 const router = createRouter({ // .... 实例化 }) router.isReady().then(()=>{ preloadRoutes(['customTabbarHomeChild']).then(res=>{ console.log(res) }); })
如上代码,preloadRoutes
函数会在路由准备就绪后预加载指定的路由组件。这样,当用户导航到 customTabbarHomeChild
时,组件已经加载完毕,从而减少了等待时间。这个函数的使用非常简单,你只需要将你所需要预加载的组件 name
传递给该函数即可完成加载。
陷阱提示
preloadRoutes
函数一定要在 router.isReady()
准备完成之后再调用,否者会加载失败。
使用技巧
preloadRoutes
函数允许你一次预加载多个路由组件,当你预加载的 name 值是嵌套子组件时,插件会自动帮你完成子级到顶级组件的组件,而非每个组件 name
都需要填写,例如,当你预加载 customTabbarHomeChild
组件时,插件会自动预加载其父级 customTabbarHome
及顶级 customTabbar
组件。
ts
/** * 目标:预加载 customTabbarHomeChild * 实际:会自动加载 customTabbar | customTabbarHome | customTabbarHomeChild */ preloadRoutes(['customTabbarHomeChild']).then(res=>{ console.log(res) }); // 等效于 preloadRoutes([ 'customTabbar', 'customTabbarHome', 'customTabbarHomeChild' ]).then(res=>{ console.log(res) });
preloadRoutes 签名
ts
function preloadRoutes(recordName: string | Array<string>): Promise<Array<{ status: 'fulfilled' | 'rejected'; value: any; }>>