我们在vue3语法糖中,如果想要利用component:is动态生成组件,可能会遇到渲染不上的问题,那么我们就可以使用如下方法来解决问题
方法1:利用defineOptions来解决
```
<template>
<component :is="comp"></component>
</template>
<script setup lang="ts">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
defineOptions({
components: {
Child1,
Child2
}
})
const index = ref(0);
const comp = index.value > 0 ? 'Child1' : 'Child2';
</script>
```
方法2:利用直接给:is的值赋值为组件
```
<template>
<component :is="comp"></component>
</template>
<script setup lang="ts">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
const index = ref(0);
const comp = index.value > 0 ? Child1 : Child2;
</script>
```
方法3:利用两个script来解决
```
<template>
<component :is="comp"></component>
</template>
<script setup lang="ts">
const index = ref(0);
const comp = index.value > 0 ? 'Child1' : 'Child2';
</script>
<script lang="ts">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
export default {
components: {
Child1,
Child2
}
}
</script>
```
方法4:直接不选择使用语法糖
```
<template>
<component :is="comp"></component>
</template>
<script lang="ts">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
export default {
data() {
return {
index: 0,
}
},
computed: {
comp() {
return this.index > 0 ? 'Child1' : 'Child2'
}
},
components: {
Child1,
Child2
}
}
</script>
```