Vue中的懒加载和按需加载

懒加载

(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.路由懒加载:


   
   
  1. export default new Router({
  2. routes:[
  3. {
  4. path: ‘/my’,
  5. name: ‘my’,
  6. //懒加载
  7. component: resolve => require([ ‘../page/my/my.vue’], resolve),
  8. },
  9. ]
  10. })

2.组件懒加载:


   
   
  1. components: {
  2. historyTab: resolve => {
  3. require([ '../../component/historyTab/historyTab.vue'],resolve)
  4. },
  5. },

3. 全局懒加载:


   
   
  1. Vue.component( 'mideaHeader', () => {
  2. System.import( './component/header/header.vue')
  3. })

按需加载

(1)按需加载原因:首屏优化,第三方组件库依赖过大,会给首屏加载带来很大的压力,一般解决方式是按需求引入组件。

(2)element-ui按需加载

element-ui 根据官方说明,先需要引入babel-plugin-component插件,做相关配置,然后直接在组件目录,注册全局组件。

1.    安装babel-plugin-component插件:

npm install babel-plugin-component –D
   
   

2.    配置插件,将 .babelrc修改为:


   
   
  1. {
  2. "presets": [
  3. [ "es2015", { "modules": false }]
  4. ],
  5. "plugins": [[ "component", [
  6. {
  7. "libraryName": "element-ui",
  8. "styleLibraryName": "theme-default"
  9. }
  10. ]]]
  11. }

3.引入部分组件,比如 Button和 Select,那么需要在 main.js中写入以下内容:


   
   
[javascript] view plain copy
print ?
  1. <code class=“language-javascript”>import Vue from ‘vue’  
  2. import { Button, Select } from ‘element-ui’  
  3. import App from ‘./App.vue’</code>  

    
    
  1. import Vue from 'vue'
  2. import { Button, Select } from 'element-ui'
  3. import App from './App.vue'

   
   
  1. Vue.component(Button.name, Button)
  2. Vue.component(Select.name, Select)
  3. /* 或写为
  4. *Vue.use(Button)
  5. *Vue.use(Select)
  6. */

(3)iView按需求加载:

import Checkbox from'iview/src/components/checkbox';
   
   

特别提醒:

1.按需引用仍然需要导入样式,即在 main.js 或根组件执行 import ‘iview/dist/styles/iview.css’;

2.按需引用是直接引用的组件库源代码,需要借助 babel进行编译,以 webpack为例:


   
   
  1. module: {
  2. rules: [
  3. { 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/ }
  4. ]
  5. }

参考链接:http://www.jb51.net/article/109865.html

转发来自 长是人千离的文章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值