当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。当我们用到它的时候才调用它,不需要的时候不调用。
下面就是vue路由懒加载的方法
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const routes = [
{
path: '/',
redirect:'/home'
},
{
path: '/home',
component: () => import('../components/Home')
},
{
path: '/about',
name: 'About',
component: () => import('../components/About')
}
]
const router = new Router({
routes,
mode:'history',
linkActiveClass:'active'
})
export default router
在网上查资料时还发现一种ES6写法,感觉也是挺不错的
import Vue from 'vue'
import Router from 'vue-router'
const Home =()=>import('../components/Home')
const About =()=>import('../components/About')
Vue.use(Router)
const routes = [
{
path: '/',
redirect:'/home'
},
{
path: '/home',
name: Home,
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = new Router({
routes,
mode:'history',
linkActiveClass:'active'
})
export default router