美文网首页
如何在vue3中通过点击按钮异步加载组件

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

作者: 青春向来如此 | 来源:发表于2021-04-17 13:01 被阅读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

    相关文章

      网友评论

          本文标题:如何在vue3中通过点击按钮异步加载组件

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