美文网首页
vue实现异步组件

vue实现异步组件

作者: 蟹老板爱写代码 | 来源:发表于2017-09-01 15:48 被阅读0次

    在大型应用中,我们可能需要将应用拆分为多个小模块,按需从服务器下载。
    如果是webpack1在vue-router可以这样写:

    {
      path: 'timeManage/reportList',
      name: 'reportList',
      component: resolve => require(['views/timeManage/reportList'], resolve)
    }
    

    如果是webpack2可以这样写

    {
      path: 'timeManage/reportList',
      name: 'reportList',
      component:() => import('views/timeManage/reportList')
    }
    

    高级写法,需要webpack2.3.0+ vue-router 2.4.0+:

    const AsyncComp = () => ({
      // 需要加载的组件. 应当是一个 Promise
      component: import('./MyComp.vue'),
      // loading 时应当渲染的组件
      loading: LoadingComp,
      // 出错时渲染的组件
      error: ErrorComp,
      // 渲染 loading 组件前的等待时间。默认:200ms.
      delay: 200,
      // 最长等待时间。超出此时间则渲染 error 组件。默认:Infinity
      timeout: 3000
    })
    

    就这么简单!~
    当导航到异步页面的时候,会请求服务端,当服务端返回资源后,才会跳转,否则会卡在那里。
    所以如果慢速网络,建议加个loading

    执行build命令后,dist/js下的资源就会如下图,红框为异步组件,被单独打包出来了

    image.png

    相关文章

      网友评论

          本文标题:vue实现异步组件

          本文链接:https://www.haomeiwen.com/subject/ewohjxtx.html