懒加载
(1)定义:懒加载也叫延迟加载,即在需要的时候进行加载,随用随载。
(2)异步加载的三种表示方法:
1. resolve => require([URL], resolve),支持性好
2. () => system.import(URL) , webpack2官网上已经声明将逐渐废除,不推荐使用
3. () => import(URL), webpack2官网推荐使用,属于es7范畴,需要配合babel的syntax-dynamic-import插件使用。
(3)Vue中懒加载的各种使用地方:
1.路由懒加载:
[JavaScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 | export default new Router({ routes:[ { path: '/my', name: 'my', //懒加载 component: resolve => require(['../page/my/my.vue'], resolve), }, ]}) |
2.组件懒加载:
[JavaScript]
纯文本查看
复制代码
1 2 3 4 5 6 7 8 9 | components: { historyTab:resolve => { require(['../../component/historyTab/historyTab.vue'],resolve) }, }, |
3. 全局懒加载:
[JavaScript]
纯文本查看
复制代码
1 2 3 4 5 | Vue.component('mideaHeader', () => { System.import('./component/header/header.vue')}) |
按需加载
(1)按需加载原因:首屏优化,第三方组件库依赖过大,会给首屏加载带来很大的压力,一般解决方式是按需求引入组件。
(2)element-ui按需加载
element-ui 根据官方说明,先需要引入babel-plugin-component插件,做相关配置,然后直接在组件目录,注册全局组件。
1. 安装babel-plugin-component插件:
npm install babel-plugin-component –D
2. 配置插件,将 .babelrc修改为:
[JavaScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 | { "presets": [ ["es2015", { "modules": false }] ], "plugins": [["component", [ { "libraryName": "element-ui", "styleLibraryName": "theme-default" } ]]]} |
3.引入部分组件,比如 Button和 Select,那么需要在 main.js中写入以下内容:
[JavaScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 | 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) /* 或写为 *Vue.use(Button) *Vue.use(Select) */ |
(3)iView按需求加载:
[JavaScript]
纯文本查看
复制代码
1 | import Checkbox from'iview/src/components/checkbox'; |
特别提醒:
1.按需引用仍然需要导入样式,即在 main.js 或根组件执行 import 'iview/dist/styles/iview.css';
2.按需引用是直接引用的组件库源代码,需要借助 babel进行编译,以 webpack为例:
[JavaScript]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 | module: { rules: [ {test: /iview.src.*?js$/, loader: 'babel' }, {test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ]} |
文章转载至:
https://blog.csdn.net/qq_30227429/article/details/75246433