路由懒加载


路由懒加载

路由懒加载的作用

路由懒加载 可以在进入路由时才加载对应的组件,因此可以缩短首屏加载时间,带来更好的用户体验

非路由懒加载

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/home'
import Index from '@/components/index'
import About from '@/components/about'
Vue.use(Router)
export default new Router({
  routes: [
    { path: '/about', component: About }, 
    { path: '/index', component: Index }, 
    { path: '/home', component: Home }
  ]
})

路由懒加载的方式

1.vue异步组件实现路由懒加载

只有当进入这个路由时,才会执行require加载组件

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  routes: [
        { 
            path: '/home', 
            name: 'home', 
            component: resolve => require(['@/components/home'],resolve) 
        },
        { 
            path: '/index', 
            name: 'index', 
            component: resolve => require(['@/components/index'],resolve) 
        },
  ]
})

2.import 实现路由懒加载

只有当进入这个路由时,才会执行import加载组件

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const Home = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
const Index = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')
export default new Router({
  routes: [
    { path: '/about', component: About }, 
    { path: '/index', component: Index }, 
    { path: '/home', component: Home }
  ]
})

简写形式

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  routes: [
    { 
        path: '/index', 
        component: () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index') 
    }, 
    { 
        path: '/home', 
        component: () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home') 
    }
  ]
})

webpackChunkName的作用

 () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
 () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')

webpackChunkName的值相同的组件会被webpack打包在一个js文件中
webpackChunkName的值不相同的组件会被webpack打包在不同的js文件中

 () => import('@/components/home')
 () => import('@/components/index')

没有webpackChunkName 默认不相同的组件会被webpack打包在不同的js文件中