Vue——路由懒加载

什么是懒加载

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

使用懒加载

  • 以下代码是常规加载方式
// index.js
// 配置路由相关信息
import VueRouter from 'vue-router'
import Vue from 'vue'

import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'

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

// 2.创建VueRouter对象
const  routes =[
  {
    // 重定向到首页,打开网页就是首页
    path: '',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/user/:abc',
    component: User
  }
]
const  router = new VueRouter({
  // 配置路由和组件之间的应用关系
  routes,
  // 将url改成常见的history模式,不用带'#'的哈希
  mode: 'history',
  linkActiveClass: 'active'
})

// 3.将router对象传入到Vue实例
export default router

  • 使用懒加载
// index.js
// 配置路由相关信息
import VueRouter from 'vue-router'
import Vue from 'vue'

// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'

// 路由懒加载
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')

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

// 2.创建VueRouter对象
const  routes =[
  {
    // 重定向到首页,打开网页就是首页
    path: '',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/about',
    component: About
  },
  {
    path: '/user/:abc',
    component: User
  }
]
const  router = new VueRouter({
  // 配置路由和组件之间的应用关系
  routes,
  // 将url改成常见的history模式,不用带'#'的哈希
  mode: 'history',
  linkActiveClass: 'active'
})

// 3.将router对象传入到Vue实例
export default router

  • 执行npm run build 命令,生成的dist文件如下

在这里插入图片描述

发布了24 篇原创文章 · 获赞 15 · 访问量 6112

猜你喜欢

转载自blog.csdn.net/weixin_42173451/article/details/104972805