什麼是懶加載
當打包構建應用時,JavaScript 包會變得非常大,影響頁面加載。如果我們能把不同路由對應的組件分割成不同的代碼塊,然後當路由被訪問的時候才加載對應組件,這樣就更加高效了。
使用懶加載
- 以下代碼是常規加載方式
// index.js
// 配置路由相關信息
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'
// 1.通過Vue.use(插件),安裝插件
Vue.use(VueRouter)
// 2.創建VueRouter對象
const routes =[
{
// 重定向到首頁,打開網頁就是首頁
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:abc',
component: User
}
]
const router = new VueRouter({
// 配置路由和組件之間的應用關係
routes,
// 將url改成常見的history模式,不用帶'#'的哈希
mode: 'history',
linkActiveClass: 'active'
})
// 3.將router對象傳入到Vue實例
export default router
- 使用懶加載
// index.js
// 配置路由相關信息
import VueRouter from 'vue-router'
import Vue from 'vue'
// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'
// 路由懶加載
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
// 1.通過Vue.use(插件),安裝插件
Vue.use(VueRouter)
// 2.創建VueRouter對象
const routes =[
{
// 重定向到首頁,打開網頁就是首頁
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:abc',
component: User
}
]
const router = new VueRouter({
// 配置路由和組件之間的應用關係
routes,
// 將url改成常見的history模式,不用帶'#'的哈希
mode: 'history',
linkActiveClass: 'active'
})
// 3.將router對象傳入到Vue實例
export default router
- 執行npm run build 命令,生成的dist文件如下