vue-router路由懒加载

require: 运行时调用,理论上可以运用在代码的任何地方,
import:编译时调用,必须放在文件开头

懒加载:component: resolve => require(['@/view/index.vue'], resolve)
用require这种方式引入的时候,会将你的component分别打包成不同的js,加载的时候也是按需加载,只用访问这个路由网址时才会加载这个js

非懒加载:component: index
如果用import引入的话,当项目打包时路由里的所有component都会打包在一个js中,造成进入首页时,需要加载的内容过多,时间相对比较长

vue的路由配置文件(routers.js),一般使用import引入的写法,当项目打包时路由里的所有component都会打包在一个js中,在项目刚进入首页的时候,就会加载所有的组件,所以导致首页加载较慢,

而用require会将component分别打包成不同的js,按需加载,访问此路由时才会加载这个js,所以就避免进入首页时加载内容过多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import Vue from 'vue'
import VueRouter from 'vue-router'
 
import Detail from '../pages/goodsDetail'
import Msg from '../components/message.vue'
// 使用路由
Vue.use(VueRouter)
export default new VueRouter({
  mode: 'history',
  routes: [
    {
      // 进行路由配置,规定'/'引入到home组件
      path: '/',
      component: resolve => require(['../pages/home.vue'], resolve),
      meta: {
        title: 'home'
      }
    },
    {
      path: '/msg',
      component: Msg
    },
    {
      path: '/detail',
      component: Detail,
      children: [
        {
          path: 'msg',
          component: Msg
        }
      ]
    }
  ]
})

  

复制代码

ES6 提出的import方法,(------最常用------)

    方法如下:const HelloWorld = ()=>import('需要加载的模块地址')

    (不加 { } ,表示直接return)



import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const HelloWorld = ()=>import("@/components/HelloWorld") export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component:HelloWorld } ] })
复制代码

 

如果用import引入的话,当项目打包时路由里的所有component都会打包在一个js中,造成进入首页时,需要加载的内容过多,时间相对比较长。
当你用require这种方式引入的时候,会将你的component分别打包成不同的js,加载的时候也是按需加载,只用访问这个路由网址时才会加载这个js。
你可以打包的时候看看目录结构就明白了。

 

 

 

转:https://www.cnblogs.com/xiaoxiaoxun/p/11001884.html

posted @   炽橙子  阅读(1337)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示