一个动态 Vue2 组件的简单工作示例
<template>
<div>
<h1>O_o</h1>
<component :is="name"/>
<button @click="onClick">Click me !</button>
</div>
</template>
<script>
export default {
data: () => ({
isShow: false
}),
computed: {
name() {
return this.isShow ? () => import('./DynamicComponent') : '';
}
},
methods: {
onClick() {
this.isShow = true;
}
},
}
</script>
一切正常,一切都很棒。开始尝试如何使用 Composition API。
<template>
<div>
<h1>O_o</h1>
<component :is="state.name"/>
<button @click="onClick">Click me !</button>
</div>
</template>
<script>
import {ref, reactive, computed} from 'vue'
export default {
setup() {
const state = reactive({
name: computed(() => isShow ? import('./DynamicComponent.vue') : '')
});
const isShow = ref(false);
const onClick = () => {
isShow.value = true;
}
return {
state,
onClick
}
}
}
</script>
我们启动,组件没有出现在屏幕上,虽然没有显示错误。还没有人搞过测试版吗?
我们将模板中的所有内容都保留在 Vue2 中
仅使用 defineAsyncComponent 在“脚本”中更改
您可以在此处了解有关 defineAsyncComponent 的更多信息 https://labs.thisdot.co/blog/async-components-in-vue-3
或在官方网站 https://v3.vuejs.org/api/global-api.html#defineasynccomponent