vue-router路由的懒加载

1.懒加载定义:

  • 官方给出了解释:

    • 当打包构建应用时,Javascript 包会变得非常大,影响页面加载。
    • 如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了
  • 理解:

    • 首先, 我们知道路由中通常会定义很多不同的页面.
    • 这个页面最后被打包在哪里呢? 一般情况下, 是放在一个js文件中.
    • 但是, 页面这么多放在一个js文件中, 必然会造成这个页面非常的大.
    • 如果我们一次性从服务器请求下来这个页面, 可能需要花费一定的时间, 甚至用户的电脑上还出现了短暂空白的情况.
    • 如何避免这种情况呢? 使用路由懒加载就可以了.
  • 路由懒加载做了什么?

    • 路由懒加载的主要作用就是将路由对应的组件打包成一个个的js代码块.
    • 只有在这个路由被访问到的时候, 才加载对应的组件
  • 这是没有使用懒加载的情况:

// 配置路由相关的信息
import VueRouter from 'vue-router';
import Vue from 'vue'

import Home from '../components/Home.vue'
import About from '../components/About.vue'
import User from '../components/User.vue'
import HomeNews from '../components/HomeNews.vue'
import HomeMessage from '../components/HomeMessage.vue'
import Profile from '../components/Profile.vue'

// 1. 通过vue.use(插件),安装插件
Vue.use(VueRouter)

// 2.创建VueRouter对象
const routes = [
  {
    path: '/',
    // redirect重定向
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    },
    children: [
      // {
      //   path: '',
      //   redirect: 'news'
      // },
      {
        path: 'news',
        component: HomeNews
      },
      {
        path: 'message',
        component: HomeMessage
      }
    ]
  },
  {
    path: '/about',
    component: About,
    meta: {
      title: '关于'
    },
    beforeEnter: (to, from, next) => {
      // console.log('about beforeEnter');
      next()
    }
  },
  {
    path: '/user/:userId',
    component: User,
    meta: {
      title: '用户'
    },
  },
  {
    path: '/Profile',
    component: Profile,
    meta: {
      title: '档案'
    },
  }
]

通过命令npm run build打包后的dist文件的情况:

  • 这是通过路由懒加载的情况:
// 配置路由相关的信息
import VueRouter from 'vue-router';
import Vue from 'vue'

const Home = () => import('../components/Home.vue')
const HomeNews = () => import('../components/HomeNews.vue')
const HomeMessage = () => import('../components/HomeMessage.vue')
const About = () => import('../components/About.vue')
const User = () => import('../components/User.vue')
const Profile = () => import('../components/Profile.vue')

通过命令npm run build打包后的dist文件的情况:

2.懒加载的方式

  • 方式一: 结合Vue的异步组件和Webpack的代码分析.
const Home = resolve => { 
    require.ensure(['../components/Home.vue'], 
    () => { 
        resolve(require('../components/Home.vue'))
    })};
  • 方式二: AMD写法
const About = resolve => require(['../components/About.vue'], resolve);
  • 方式三: 在ES6中, 我们可以有更加简单的写法来组织Vue异步组件和Webpack的代码分割.
const Home = () => import('../components/Home.vue')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值