最近研究了vue性能优化,涉及到vue异步组件和懒加载。一番研究得出如下的解决方案。
原理:利用webpack对代码进行分割是懒加载的前提,懒加载就是异步调用组件,需要时候才下载。
案例:
首先是组件,创建四个组件分别命名为first、second、three和four;内容如下
first <template> <div>我是第一个页面</div> </template> second <template> <div>我是第二个页面</div> </template> three <template> <div>我是第三个页面</div> </template> four <template> <div>我是第四个页面</div> </template>
路由index.js代码,异步组件方式有两种,代码中的方案1和方案2;注意:方案1需要添加syntax-dynamic-import插件
import Vue from 'vue' import VueRouter from 'vue-router' /*import First from '@/components/First' import Second from '@/components/Second'*/ Vue.use(VueRouter) //方案1 const first =()=>import(/* webpackChunkName: "group-foo" */ "../components/first.vue"); const second = ()=>import(/* webpackChunkName: "group-foo" */ "../components/second.vue"); const three = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/three.vue"); const four = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/four.vue"); //方案2 const first = r => require.ensure([], () => r(require('../components/first.vue')), 'chunkname1') const second = r => require.ensure([], () => r(require('../components/second.vue')), 'chunkname1') const three = r => require.ensure([], () => r(require('../components/three.vue')), 'chunkname2') const four = r => require.ensure([], () => r(require('../components/four.vue')), 'chunkname2') //懒加载路由 const routes = [ { //当首次进入页面时,页面没有显示任何组件;让页面一加载进来就默认显示first页面 path:'/', //重定向,就是给它重新指定一个方向,加载一个组件; component:first }, { path:'/first', component:first }, { path:'/second', component:second }, { path:'/three', component:three }, { path:'/four', component:four } //这里require组件路径根据自己的配置引入 ] //最后创建router 对路由进行管理,它是由构造函数 new vueRouter() 创建,接受routes 参数。 const router = new VueRouter({ routes }) export default router;
最后,如果想要让build之后的代码更便于识别,配置webpack代码
运行 npm run build结果
注意方案1和方案2只能用一个。然后运行项目试验一下就可以了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年10月04日
2024年10月04日
- 潘美辰.2006-最冷的夏天(引进版)【美梦辰真】【WAV+CUE】
- 班得瑞原装进口《第十张新世纪专辑:月光水岸》1CD[APE/CUE分轨][277.2MB]
- 班得瑞原装进口《第十一张新世纪专辑:雾色山脉》1CD[APE/CUE分轨][291.6MB]
- 班得瑞原装进口《第十二张新世纪专辑:翡翠谷》1CD[APE/CUE分轨][307.9MB]
- 高卿尘.2024-情绪商店【Hahahai】【FLAC分轨】
- 王恩喆.2024-黄沙【KOOD】【FLAC分轨】
- 邓丽君.1983-漫步人生路(2024环球MQA-UHQCD限量版)【环球】【WAV+CUE】
- 陈容森.1996-情断【上华】【WAV+CUE】
- 裘海正.1994-爱我的人和我爱的人【上华】【WAV+CUE】
- 庾澄庆.1988-错过的爱【福茂】【WAV+CUE】
- 班得瑞原装进口《第十三张新世纪专辑:旭日之丘》1CD[APE/CUE分轨][329.6MB]
- 纯音入心系列纯音乐《古筝|佛蕴|境法禅心意法自然》1CD[MP3][350MB]
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[320K/MP3][203.44MB]
- 群星.1981-名曲65(2014环球复黑王·百代篇)【EMI百代】【WAV+CUE】
- 陈淑桦.1990-娃娃的故事【柯达】【WAV+CUE】