Vue3 局部无注册动态渲染组件

3,773 阅读1分钟
<template v-for="c in components" :key="c">
  <component :is="c"></component>
</template>

<script setup>
import { h, markRaw, ref } from "vue";

const MyComponent = markRaw({
  data() {
    return { count: 1 };
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  render() {
    return h("div", this.count);
  }
});

const components = ref([]);

components.value.push(MyComponent);

setTimeout(() => {
  components.value.push(MyComponent);
}, 2000);
</script>