Search code examples
vue.jsvue-component

inject render method into template


Must the render method of a Vue component be used exclusively or can it be combined with a template? Most of my component can be rendered using a template but just need a small part of it to be rendered using code. If this is possible how can I combine the render method output with the template?

Example in component:

<template>
   <table>
      <tr>
        // use render method here
      </tr>
      <tr v-for="row in rows">
        // use render method here
      </tr>  
   </table>
</template>

Need render method in spots above to loop through the array $scopedSlots.column and render each <th> and <td> based on multiple <templates v-slot:column={row}> provided by parent.


Solution

  • As far as I know you can either use the render function or a template - but not both. They can not be combined.

    What you could do to make your example work is to use the v-html-directive, which updates the innerHTML of an element https://012.vuejs.org/api/directives.html#v-html.

    new Vue({
      el: '#el',
      data: {
        rows: ['row1', 'row2', 'row3']
      },
      methods: {
        renderRow(row) {
          return `<td>${row}</td>`;
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="el">
      <table>
        <tr v-for="row in rows" v-html="renderRow(row)">
        
        </tr>
      </table>
    </div>