Home > OS >  vue3, How to use dynamic component in tsx
vue3, How to use dynamic component in tsx

Time:11-05

Failed to resolve component: component If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.

<script lang="tsx">

export default defineComponent({

 setup(props) {
     return () => (
      <n-form>
        {list.value.map(item => {
          return (
            <n-form-item>
    
                <component is="*****" ></component>

            </n-form-item>
          );
        })}
      </n-form>
    );
}

})
</script>

CodePudding user response:

<component is="*****" ></component> will not work using JSX.

instead you can just pass the component itself

import Comp1 from "./Comp1.vue";

export default defineComponent({

  setup(props) {
    return () => (
      <n-form>
        {list.value.map(item => {
          const MyComponent = Comp1;
          return (
            <n-form-item>

                <MyComponent/>

            </n-form-item>
          );
        })}
      </n-form>
    );
  }
})

of course, using const MyComponent = Comp1; is not exactly dynamic, but you can replace that with a lookup like

import Comp1 from "./Comp1.vue";
import Comp2 from "./Comp2.vue";
import Comp3 from "./Comp3.vue";
cons componentDefs = {
   "comp-1": Comp1,
   "comp-2": Comp2,
   "comp-3": Comp3,
}

and then you can look them up with

const MyComponent = componentDefs[*******];
  • Related