Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 376
Brobic Vripiat Avatar asked May 28 '26 20:05

Brobic Vripiat


2 Answers

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>
like image 163
Reynicke Avatar answered May 30 '26 10:05

Reynicke


I'm having this same challenge as well. Which is how I came to your question.

As others have said, it seems you can either use a template or render function but not both.

My suggestion would be to have a component handle only the render function, while the parent component can use the template method

So, Per your example

<template>
   <table>
      <tr>
        <component-using-only-render-method />
      </tr>
      <tr v-for="row in rows">
        <component-using-only-render-method />
      </tr>  
   </table>
</template>

I think its the best of both worlds with minimal compromise

like image 31
Audacitus Avatar answered May 30 '26 10:05

Audacitus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!