懶加載
(1)定義:懶加載也叫延遲加載,即在需要的時(shí)候進(jìn)行加載,隨用隨載。
(2)異步加載的三種表示方法:
1.resolve => require([URL], resolve),支持性好
2.() => system.import(URL) , webpack2官網(wǎng)上已經(jīng)聲明將逐漸廢除,不推薦使用
3.() => import(URL), webpack2官網(wǎng)推薦使用,屬于es7范疇,需要配合babel的syntax-dynamic-import插件使用。
(3)vue中懶加載的流程:

(4)Vue中懶加載的各種使用地方:
1.路由懶加載:
export default new Router({
routes:[
{
path: '/my',
name: 'my',
//懶加載
component: resolve => require(['../page/my/my.vue'], resolve),
},
]
})
2.組件懶加載:
components: {
historyTab:resolve => {
require(['../../component/historyTab/historyTab.vue'],resolve)
},
},
3.全局懶加載:
Vue.component('mideaHeader', () => {
System.import('./component/header/header.vue')
})
按需加載
(1)按需加載原因:首屏優(yōu)化,第三方組件庫依賴過大,會(huì)給首屏加載帶來很大的壓力,一般解決方式是按需求引入組件。
(2)element-ui按需加載
element-ui根據(jù)官方說明,先需要引入babel-plugin-component插件,做相關(guān)配置,然后直接在組件目錄,注冊(cè)全局組件。
1.安裝babel-plugin-component插件:
npm install babel-plugin-component –D
2.配置插件,將.babelrc修改為:
{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [["component", [
{
"libraryName": "element-ui",
"styleLibraryName": "theme-default"
}]]]}
3.引入部分組件,比如Button和Select,那么需要在main.js中寫入以下內(nèi)容:
import Vue from 'vue'
import { Button, Select } from 'element-ui'
import App from './App.vue'
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)
/*或?qū)憺?/p>
*Vue.use(Button)
*Vue.use(Select)
*/
(3)iView按需求加載:
import Checkbox from'iview/src/components/checkbox';
特別提醒:
1.按需引用仍然需要導(dǎo)入樣式,即在main.js或根組件執(zhí)行import 'iview/dist/styles/iview.css';
2.按需引用是直接引用的組件庫源代碼,需要借助babel進(jìn)行編譯,以webpack為例:
module: {
rules: [
{test: /iview.src.*?js$/, loader: 'babel' },
{test: /\.js$/, loader: 'babel', exclude: /node_modules/ }
]
}
參考鏈接:http://www.jb51.net/article/109865.htm