如何在vue3中通过点击按钮异步加载组件

2021-04-17  本文已影响0人  青春向来如此

方式一:

<template>
  <button @click="handleClick">点击异步加载组件</button>
  <component :is="currentTabComponent"></component>
</template>
<script>
import { defineAsyncComponent, shallowRef } from "vue";
export default {
  setup() {
    const currentTabComponent = shallowRef(null);

    const handleClick = () => {
      currentTabComponent.value = defineAsyncComponent(() => import("./components/AsyncComponent.vue"));
    };
    return {
      handleClick,
      currentTabComponent,
    };
  },
};
</script>

方式二:

<template>
  <button @click="handleClick">点击异步加载组件</button>
  <AsyncComponent v-if="show" />
</template>
<script>
import { defineAsyncComponent, ref, shallowRef } from "vue";
export default {
  components: {
    AsyncComponent: defineAsyncComponent(() => import("./components/AsyncComponent.vue")),
  },
  setup() {
    const show = ref(false);
    const handleClick = () => {
      show.value = true;
    };
    return {
      handleClick,
      show,
    };
  },
};
</script>

点击加载按钮前如下图:


加载前.png

点击加载按钮后如下图:


加载后.png
上一篇下一篇

猜你喜欢

热点阅读