vue中的懶加載和按需加載

vue中的懶加載和按需加載

懶加載

(1)定義:懶加載也叫延遲加載,即在需要的時候進(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)
  },   
},
  1. 全局懶加載:
Vue.component('mideaHeader', () => {
System.import('./component/header/header.vue')
})

按需加載

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

(2)element-ui按需加載

element-ui 根據(jù)官方說明,先需要引入babel-plugin-component插件,做相關(guān)配置,然后直接在組件目錄,注冊全局組件。

  1. 安裝babel-plugin-component插件:
npm install babel-plugin-component –D
  1. 配置插件,將 .babelrc修改為:
{
"presets": [
  ["es2015", { "modules": false }]
 ],
"plugins": [["component", [
   {
    "libraryName": "element-ui",
    "styleLibraryName": "theme-default"
   }
 ]]]
}

3.引入部分組件,比如 Button和 Select,那么需要在 main.js中寫入以下內(nèi)容:

  1. <code class="language-javascript">import Vue from 'vue'
  2. import { Button, Select } from 'element-ui'
  3. import App from './App.vue'</code>
Vue.component(Button.name, Button)Vue.component(Select.name, Select) /* 或?qū)憺?*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/ }
   ]
}

如下例子中:
//懶加載路由

const routes = [
  {          //當(dāng)首次進(jìn)入頁面時,頁面沒有顯示任何組件;讓頁面一加載進(jìn)來就默認(rèn)顯示first頁面
    path:'/',   //重定向,就是給它重新指定一個方向,加載一個組件;
    component:resolve => require(['@/components/First'],resolve)
  },
  {
    path:'/first',
    component:resolve => require(['@/components/First'],resolve)
  },
  {
    path:'/second',
    component: resolve => require(['@/components/Second'],resolve)
  }
//這里require組件路徑根據(jù)自己的配置引入
]
//最后創(chuàng)建router 對路由進(jìn)行管理,它是由構(gòu)造函數(shù) new vueRouter() 創(chuàng)建,接受routes 參數(shù)。
 
 const router = new VueRouter({
 routes
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容