路由中的Vue JS动态组件。处理加载和错误

时间:2019-05-29 10:53:39

标签: javascript vue.js vuejs2

在我的Vue应用程序中,我正在动态导入组件,然后在路由中使用这些组件。因此,当您转到特定的路线时,将动态获取组件块。

有时会花费一些时间来获取组件,并且有时由于网络错误而无法获取组件。因此,我想了解如何优雅地处理错误并加载状态。

2 个答案:

答案 0 :(得分:0)

如果您使用axios来处理您的请求,则可以拦截任何请求并根据那里的状态来处理它们。

这是一个示例,如果响应返回错误代码为401(未经授权),则该示例将重定向到Login。 要提及的一件事是,您可以具有用于响应和请求的拦截器。

文档:https://github.com/axios/axios

axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response.status === 401) {
        router.push('/logout');
    }

    return error;
});

答案 1 :(得分:0)

Vue允许您将组件定义为异步解析组件定义的工厂函数。这称为异步组件工厂。

通常,当我们用Webpack延迟加载路由器视图时,我们这样做:

export default [
  {
    path: '/',
    name: 'home',
    component: () => import('@views/home'),
    //               ^^^^^^^^^^^^^^^^^^^^^
    //               The `import` function returns a Promise with our component definition.
  },
] // RouteConfig[]

但是,当我们需要handle the loading state时会发生什么?

由于Vue 2.3.0和Vue Router 2.4.0,异步组件工厂也可以返回对象:

export default [
  {
    path: '/',
    name: 'home',
    component: () => ({
      // The component to load (should be a Promise)
      component: import('./MyComponent.vue'),
      // A component to use while the async component is loading
      loading: LoadingComponent,
      // A component to use if the load fails
      error: ErrorComponent,
      // Delay before showing the loading component. Default: 200ms.
      delay: 200,
      // The error component will be displayed if a timeout is
      // provided and exceeded. Default: Infinity.
      timeout: 3000
    })
  },
] // RouteConfig[]

您可能想对不同的视图重用相同的加载和错误组件,以及一些延迟和超时默认值。在这种情况下,您可以使用由Vue核心团队成员vue enterprise boilerplate创建的Chris Fritz中的策略。

// Lazy-loads view components, but with better UX. A loading view
// will be used if the component takes a while to load, falling
// back to a timeout view in case the page fails to load. You can
// use this component to lazy-load a route with:
//
// component: () => lazyLoadView(import('@views/my-view'))
//
// NOTE: Components loaded with this strategy DO NOT have access
// to in-component guards, such as beforeRouteEnter,
// beforeRouteUpdate, and beforeRouteLeave. You must either use
// route-level guards instead or lazy-load the component directly:
//
// component: () => import('@views/my-view')
//
function lazyLoadView(AsyncView) {
  const AsyncHandler = () => ({
    component: AsyncView,
    // A component to use while the component is loading.
    loading: require('@views/_loading').default,
    // Delay before showing the loading component.
    // Default: 200 (milliseconds).
    delay: 400,
    // A fallback component in case the timeout is exceeded
    // when loading the component.
    error: require('@views/_timeout').default,
    // Time before giving up trying to load the component.
    // Default: Infinity (milliseconds).
    timeout: 10000,
  })

  return Promise.resolve({
    functional: true,
    render(h, { data, children }) {
      // Transparently pass any props or children
      // to the view component.
      return h(AsyncHandler, data, children)
    },
  })
}

并像这样使用它:

export default [
  {
    path: '/',
    name: 'home',
    component: () => lazyLoadView(import('@views/home')),
  },
] // RouteConfig[]