Search code examples
vue.jsvue-componentvuejs3vue-composition-apivue-script-setup

Vue3 dynamic render


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 class="example">
      <template v-for="(item, index) in myConfig" :key="index">
        My Button:
        <div class="example-2">{{ item.renderer() }}</div>
      </template>
    </div>
  </template>

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

How I can do it?


Solution

  • 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 class="example-2">
            <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>