在項目的目錄中找到router文件夾里的index.js index.js文件原先的文件結構 import Vue from 'vue' import Router from 'vue-router' import Home from '@/pages/home/Home' import City from '@/pages/city/City' import Detail from '@/pages/detail/Detail' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Home', component: Home }, { path: '/city', name: 'City', component: City }, { path: '/detail/:id', name: 'Detail', component: Detail }], scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } }) 修改后的index.js文件結構 import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Home', component: () => import('@/pages/home/Home') }, { path: '/city', name: 'City', component: () => import('@/pages/city/City') }, { path: '/detail/:id', name: 'Detail', component: () => import('@/pages/detail/Detail') }], scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } } }) 注意:當app.js文件很小或者不超過1MB的時候我們沒必要把app.js拆分進行異步加載,這樣就不會造成多余的http請求了,否則的話就會降低頁面的性能
頁面中的異步加載組件 我們不單單可以在路由中使用異步加載組件,在一個頁面中也可以使用 如頁面中異步加載Header.vue組件 原先的寫法 <script> import HomeHeader from './components/Header' export default { components: { HomeHeader } } </script> 異步加載的寫法 <script> export default { components: { HomeHeader: () => import('./components/Header') } } </script>
頁面組件按需加載總結
1,使用vue異步組件,可以將復雜頁面的框架代碼和子組件代碼拆開,優先加載框架代碼,顯著提高頁面加載速度;
2,組織復雜頁面的代碼時,可以考慮對於打開首屏時不需要渲染的子組件,使用v-if
控制其只在需要的時候被渲染。