Vue.js前端Vue专辑

Vue 路由配置防止组件重复加载注销,使组件复用减少资源消耗

2020-03-13  本文已影响0人  承诺一时的华丽

最近再做前端优化的时候发现,同一个组件在不同层级的路由进行注册,当在不同层级的路由中进行页面跳转会重复销毁加载

一、问题复现

[{
  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.vuethis.$router.push({name: 'detail'})。这种路由配置将导致layoutHeaderAside组件重复销毁beforeDestroy()加载mounted()

二、问题优化

[{
  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')
        }
      ]
    }
  ]
}]
<template>
<div>
    <router-view></router-view>
</div>
</template>

<script>
export default {
  name: 'BlankLayout'
}
</script>

<style scoped>
</style>
import BlankLayout from '@/layout/BlankLayout'
上一篇下一篇

猜你喜欢

热点阅读