vue3 动态组件 使用component :is 加载组件的四种方法

7,805 阅读1分钟

1 不使用setup语法糖,绑定字符串

<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>
<style scoped></style>

2 使用setup语法糖,绑定组件实例

<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>
<style scoped></style>

3 使用setup语法糖,绑定字符串(添加选项式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>
<style scoped></style>

4 使用setup语法糖,绑定字符串(defineOptions,vue版本3.3)

<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>
<style scoped></style>