Vue 的文档提到异步组件的概念,特别异步组件处理加载状态的内容:

vuerouterloading

注意如果你希望在 Vue Router 的路由组件中使用上述语法的话,你必须使用 Vue Router 2.4.0+ 版本

好吧,经过测试在路由配置上根本不管用。详细内容可见我在官方论坛的文章和Github Issue

Vue Router 懒加载组件状态不支持loading属性 - Vue Form

我的解决方案跟Github中Pull Request差不多,都是用一个功能性组件做为lazy load的组件,挂在Router上,并处理加载状态。

import Vue from 'vue'
import Router from 'vue-router'
import Loading from './components/Loading.vue'

Vue.use(Router)

const AsyncLoad = component => new Promise((resolve) => {
  const load = () => ({ component, loading: Loading })
  resolve({
    functional: true,
    name: 'AsyncLoad',
    render: h => h(load)
  })
})

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      redirect: '/Dashboard'
    },
    {
      path: '/Dashboard',
      name: 'Dashboard',
      component: () => AsyncLoad(import(/* webpackChunkName: "Dashboard" */ './views/Dashboard.vue'))
    },
    {
      path: '/Map',
      name: 'Map',
      component: () => AsyncLoad(import(/* webpackChunkName: "Map" */ './views/Map.vue'))
    },
    {
      path: '/SystemConfiguration',
      name: 'System Configuration',
      component: () => AsyncLoad(import(/* webpackChunkName: "SystemConfiguration" */ './views/SystemConfiguration.vue'))
    },
    {
      path: '/DeviceManagement',
      name: 'Device Management',
      component: () => AsyncLoad(import(/* webpackChunkName: "DeviceManagement" */ './views/DeviceManagement.vue'))
    },
    {
      path: '*',
      name: '404 Not Found',
      component: () => AsyncLoad(import(/* webpackChunkName: "404NotFound" */ './views/ErrorNotFound.vue'))
    }
  ]
})

其中我还发现如果AsyncLoad写成这样会造成Vue死循环:

const AsyncLoad = component => new Promise((resolve) => {
  resolve({
    functional: true,
    name: 'AsyncLoad',
    render: h => h(() => ({ component, loading: Loading }))
  })
})

也就是说const load = () => ({ component, loading: Loading })必须在render函数之外,不然每次render都会创建一个新的异步组件,无法完成异步组件的加载。

Vue的开发还是很热闹的,有很多大神在积极贡献自己的力量,虽然文档描述有误,社区的响应还是很积极的。以后遇到问题还是要先翻翻Github看看有没有人提到相关问题。

原文链接:https://marskid.net/2018/11/11/vue-router-lazy-loading/