vue 路由懒加载

时间:2021-10-11
本文章向大家介绍vue 路由懒加载,主要包括vue 路由懒加载使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

懒加载:也叫延迟加载,即在需要的时候进行加载,随用随载。    

 使用懒加载的原因: vue是单页面应用,使用webpcak打包后的文件很大,会使进入首页时,加载的资源过多,页面会出现白屏的情况,不利于用户体验。运用懒加载后,就可以按需加载页面,提高用户体验。

整个网页默认是刚打开就去加载所有页面,路由懒加载就是只加载你当前点击的那个模块。

按需去加载路由对应的资源,提高首屏加载速度(tip:首页不用设置懒加载,而且一个页面加载过后再次访问不会重复加载)。

实现原理:将路由相关的组件,不再直接导入了,而是改写成异步组件的写法,只有当函数被调用的时候,才去加载对应的组件内容。

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  mode: 'history',
  routes: [
   {
      path: '/',
      component: resolve => require(['@/components/DefaultIndex'],resolve),
      children: [
        {
          path: '',
          component: resolve => require(['@/components/Index'],resolve)
        },
        {
          path: '*',
          redirect: '/Index'
        }
      ]
})

传统路由配置

import Vue from 'vue'
import Router from 'vue-router'
import DefaultIndex from '@/components/DefaultIndex'
import Index from '@/components/Index'
Vue.use(Router)
export default new Router({
  mode: 'history',
  routes: [
   {
      path: '/',
      component: 'DefaultIndex ',
      children: [
        {
          path: '',
          component: 'Index'
        },
        {
          path: '*',
          redirect: '/Index'
        }
      ]
})

原文地址:https://www.cnblogs.com/ddqyc/p/15394334.html