方式一:
<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
网友评论