Home > Software design >  Vue3 dynamic render
Vue3 dynamic render

Time:03-28

I have a list of components and I want to set a config for them from outside,

For example:

 const myConfig = [
  {
    name: 'example',
    renderer: () => (<button @click="clickHanlder">Click me!</button>)
  },
  ...
 ];

And for my component I want to use myConfig as shown below:

  <template>
    <div >
      <template v-for="(item, index) in myConfig" :key="index">
        My Button:
        <div >{{ item.renderer() }}</div>
      </template>
    </div>
  </template>

Please pay attention that I don't want to use slots

How I can do it?

CodePudding user response:

You could achieve that by using h render function as shown in the following example :

<template v-for="(item, index) in myConfig" :key="index">
    My Button:
    <div >
        <component :is="item.renderer" />
    </div>
</template>
<script setup lang="ts">

import {  h } from 'vue';

const myConfig = [
  {
    name: 'example',
    renderer: h('button', {
  
      onClick:clickHanlder
      
    },'Click me !'),
  },

 ];

 function clickHanlder(){
    console.log('click btn');
 }

</script>

  • Related