路由懶加載
路由懶加載的作用
路由懶加載 可以在進入路由時才加載對應的組件,因此可以縮短首屏加載時間,帶來更好的用戶體驗
非路由懶加載
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文件中