Vue3.0破坏性变化----异步组件

vue3.0中异步组件要求使用defineAsyncComponent方法创建

由于vue3中函数式组件必须定义为纯函数,异步组件定义是有如下变化

  • 必须明确使用defineAsyncComponent包裹
  • component重命名为loader
    loading重命名为loadingComponent
    error重命名为errorComponent
  • loader函数不再接收resolve,reject且必须返回一个Promise

Vue3.0中异步组件的使用

在组件中使用

<template>
  <async-comp-test> </async-comp-test>
</template>
<script lang='ts'>
import { defineAsyncComponent, defineComponent, h } from "vue";
export default defineComponent({
  data() {
    return {};
  },
  components: {
    AsyncCompTest: defineAsyncComponent({
      //   loader: () => import("@/components/AsyncCompTest.vue"),//正常写法
      loader: () => {
        return new Promise((resolve) => {
          setTimeout(() => {
            require(["@/components/AsyncCompTest.vue"], resolve);
          }, 4000);
        });
      }, //模拟网络延时
      delay: 200,
      timeout: 3000,
      loadingComponent: {
        render() {
          return h("p", "加载中...");
        },
      },
      errorComponent: {
        render() {
          return h("p", "加载失败");
        },
      },
    }),
  },
});
</script>

Vue2.0中异步组件的使用

在组件中使用

<template>
  <div>
    <h1>异步组件</h1>
    <async-comp-test></async-comp-test>
  </div>
</template>
<script>
export default {
  components: {
    AsyncCompTest: () => ({
      // component: import("./Functional.vue"),//正常写法
      component: new Promise((resolve) => {
        setTimeout(() => {
          require(["./Functional.vue"], resolve);
        }, 2000);
      }), //模拟网络延时
      loading: {
        render(h) {
          return h("p", "加载中...");
        },
      },
      error: {
        render(h) {
          return h("p", "加载失败!");
        },
      },
      delay: 200,
      timeout: 3000,
    }),
  },
  data() {
    return {};
  },
};
</script>

在路由中使用

function lazyLoadView (asyncComp) {
  const AsyncHandler = () => ({
    component: asyncComp,//示例:import('******')
    loading: require ('../components/Loading'),
    delay: 200,

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

const asyncComp = import ('../components/AsyncComponent.vue');
const router = new Router ({
  routes: [
    {
      path: '/asyncComponent',
      component: () => lazyLoadView (asyncComp),
    },
  ],
});

推荐阅读更多精彩内容