Vue.js 为什么动态组件在vue3中不工作?
以下是一个工作的Vue2示例:Vue.js 为什么动态组件在vue3中不工作?,vue.js,vuejs3,Vue.js,Vuejs3,以下是一个工作的Vue2示例: <template> <div> <h1>O_o</h1> <component :is="name"/> <button @click="onClick">Click me !</button> </div> </template> <script> export def
<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>
欧欧欧
点击我!
导出默认值{
数据:()=>({
伊莎:错
}),
计算:{
姓名(){
返回this.isShow?()=>import('./DynamicComponent'):'';
}
},
方法:{
onClick(){
this.isShow=true;
}
},
}
在Vue3选项下重做无效。不会发生错误,但组件不会出现
<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>
欧欧欧
点击我!
从“vue”导入{ref,被动,计算}
导出默认值{
设置(){
常数状态=无功({
名称:computed(()=>isShow?导入('./DynamicComponent.vue'):'')
});
常量isShow=ref(假);
const onClick=()=>{
isShow.value=true;
}
返回{
国家,,
onClick
}
}
}
有人研究过vue2测试版吗?请帮帮我。很抱歉语言笨拙,我使用谷歌翻译。使用“观察”一切正常
<template>
<component :is="componentPath"/>
</template>
<script lang="ts">
import {defineComponent, ref, watch, SetupContext} from "vue";
export default defineComponent({
props: {
path: {type: String, required: true}
},
setup(props: { path: string }, context: SetupContext) {
const componentPath = ref("");
watch(
() => props.path,
newPath => {
if (newPath !== "")
import("@/" + newPath + ".vue").then(val => {
componentPath.value = val.default;
context.emit("loaded", true);
});
else {
componentPath.value = "";
context.emit("loaded", false);
}
}
);
return {componentPath};
}
});
</script>
从“vue”导入{defineComponent,ref,watch,SetupContext};
导出默认定义组件({
道具:{
路径:{type:String,必需:true}
},
设置(props:{path:string},context:SetupContext){
常量componentPath=ref(“”);
监视(
()=>道具路径,
新路径=>{
如果(新路径!==“”)
导入(“@/”+newPath+“.vue”)。然后(val=>{
componentPath.value=val.default;
emit(“loaded”,true);
});
否则{
componentPath.value=“”;
emit(“已加载”,false);
}
}
);
返回{componentPath};
}
});
将模板中的所有内容保留为Vue2
欧欧欧
点击我!
仅在“设置”中使用defineAsyncComponent进行更改
您可以在此处了解有关defineAsyncComponent的更多信息
const isShow=ref(false);
const name=computed(()=>isShow.value?defineAsyncComponent(()=>import(“./DynamicComponent.vue”):“”)
const onClick=()=>{
isShow.value=true;
}
像这样试试<代码>异步()=>等待导入('./DynamicComponent')我试过了。不幸的是,一切都没有改变。嗨@progervova,这方面有什么更新吗?我也处于同样的情况是的,这解决了Vue 3和安装异步组件的问题。这应该被接受为答案。