Vue 路由配置防止组件重复加载注销,使组件复用减少资源消耗
2020-03-13 本文已影响0人
承诺一时的华丽
最近再做前端优化的时候发现,同一个组件在不同层级的路由进行注册,当在不同层级的路由中进行页面跳转会重复销毁加载
一、问题复现
- 同一组件
layoutHeaderAside
在不同层级的路由配置
[{
path: '/',
redirect: { name: 'index' },
component: layoutHeaderAside,
children: [
{
path: 'index',
name: 'index',
component: () => import('@/pages/index')
},
{
path: 'list',
name: 'list',
component: () => import('@/pages/list')
}
]
},
{
path: '/detail',
redirect: { name: 'detail' },
component: layoutHeaderAside,
children: [
{
path: 'detail',
name: 'detail',
component: () => import('@/pages/detail')
},
{
path: 'info',
name: 'info',
component: () => import('@/pages/info')
}
]
}]
假设在
index.vue
进行页面跳转到detail.vue
:this.$router.push({name: 'detail'})
。这种路由配置将导致layoutHeaderAside组件重复销毁beforeDestroy()
加载mounted()
二、问题优化
- 将路由合并, 通过
BlankLayout
(空白组件),就可以同时共用layoutHeaderAside
组件,同时又支持当前路由组下级公共配置
[{
path: '/',
redirect: { name: 'index' },
component: layoutHeaderAside,
children: [
{
path: 'index',
name: 'index',
component: () => import('@/pages/index')
},
{
path: 'list',
name: 'list',
component: () => import('@/pages/list')
},
{
path: '/detail',
redirect: { name: 'detail' },
component: BlankLayout, //BlankLayout为空白组件,就可以同时共用layoutHeaderAside组件,同时又支持当前路由组下级的公共配置
children: [
{
path: 'detail',
name: 'detail',
component: () => import('@/pages/detail')
},
{
path: 'info',
name: 'info',
component: () => import('@/pages/info')
}
]
}
]
}]
BlankLayout.vue
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'BlankLayout'
}
</script>
<style scoped>
</style>
- 引用方式
import BlankLayout from '@/layout/BlankLayout'
-
路由跳转原理图解
如果频繁的页面切换,将导致大量的资源消耗
image.png