1. 程式人生 > >vue 懶加載

vue 懶加載

them pla 按需加載 line 三方 copy 異步 地方 ()

懶加載

(1)定義:懶加載也叫延遲加載,即在需要的時候進行加載,隨用隨載。

(2)異步加載的三種表示方法:

1. resolve => require([URL], resolve),支持性好
2. () => system.import(URL) , webpack2官網上已經聲明將逐漸廢除,不推薦使用
3. () => import(URL), webpack2官網推薦使用,屬於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),
},
]
})
1
2.組件懶加載:
components: {
historyTab:resolve => {
require([‘../../component/historyTab/historyTab.vue‘],resolve)
},
},
1
3. 全局懶加載:
Vue.component(‘mideaHeader‘, () => {
System.import(‘./component/header/header.vue‘)
})
1
按需加載

(1)按需加載原因:首屏優化,第三方組件庫依賴過大,會給首屏加載帶來很大的壓力,一般解決方式是按需求引入組件。

(2)element-ui按需加載

element-ui 根據官方說明,先需要引入babel-plugin-component插件,做相關配置,然後直接在組件目錄,註冊全局組件。
1. 安裝babel-plugin-component插件:
npm install babel-plugin-component –D
1
2. 配置插件,將 .babelrc修改為:

{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [["component", [
{
"libraryName": "element-ui",
"styleLibraryName": "theme-default"
}
]]]
}
1
3.引入部分組件,比如 Button和 Select,那麽需要在 main.js中寫入以下內容:
1
[javascript] view plain copy
<code class=“language-javascript”>import Vue from ‘vue’
import { Button, Select } from ‘element-ui’
import App from ‘./App.vue’</code>
import Vue from ‘vue‘
import { Button, Select } from ‘element-ui‘
import App from ‘./App.vue‘
1
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)

/* 或寫為
*Vue.use(Button)
*Vue.use(Select)
*/
1
(3)iView按需求加載:

import Checkbox from‘iview/src/components/checkbox‘;
1
特別提醒:
1.按需引用仍然需要導入樣式,即在 main.js 或根組件執行 import ‘iview/dist/styles/iview.css’;
2.按需引用是直接引用的組件庫源代碼,需要借助 babel進行編譯,以 webpack為例:
module: {
rules: [
{test: /iview.src.*?js$/</span>, <span class="hljs-attr">loader</span>: <span class="hljs-string">‘babel‘</span> },</div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="4"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> {<span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.js$/, loader: ‘babel‘, exclude: /node_modules/ }
]
}

vue 懶加載