解析vue路由异步组件和懒加载案例

(编辑:jimmy 日期: 2025/9/23 浏览:2)

最近研究了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代码

解析vue路由异步组件和懒加载案例

运行 npm run build结果

解析vue路由异步组件和懒加载案例

注意方案1和方案2只能用一个。然后运行项目试验一下就可以了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一句话新闻

一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?