Home > Net >  Adding custom HTML element inside template using functions Vue.js
Adding custom HTML element inside template using functions Vue.js

Time:02-02

Is there any way to render html element with custom properties inside template tag using javascript functions?

Example what I try to achieve:

<template>
  <div >
    {{ testFunction(param1,param2,param3) }}
  </div>
</template>


<script>
export default {
....
  methods: {
    testFunction(param1,param2,param3) {
      return `<button @click="function()">Click</button>`;
   }
  }
};
</script>

CodePudding user response:

Directly you will get interpolated html, like this

<button @click="function()">Click</button>

Even if you fix it using the v-html directive to output raw HTML the button will still not work.

The right way is to use Render Functions like this:

const myComponent3 = {   
  setup(props) {
    return () => h('button',  
      {
        onClick(event) {
          alert('Click');
        }
      },
      'Click Me!'
    )
  }
}

Here is the playground with samples:

const { createApp, h } = Vue;

const myComponent1 = {   
  template: '#my-component',
  methods: {
    testFunction(par1) {
      return `<button @click="function()">Click</button>`;
    }
  }
}

const myComponent2 = {   
  template: '<div v-html="rawHTML()"></div>',
  methods: {
    myClick() {    
      alert('Click');
    },
    rawHTML(par1) {
      return '<button @click="myClick()">Click</button>';
    }
  }
}

const myComponent3 = {   
  setup(props) {
    return () => h('button',  
      {
        onClick(event) {
          alert('Click');
        }
      },
      'Click Me!'
    )
  }
}

const App = {
  components: { 
    myComponent1,  myComponent2, myComponent3
  }
}

const app = createApp(App)
app.mount('#app')
<div id="app">  
  My Component 1: <my-component1></my-component1><br/>
  My Component 2: <my-component2></my-component2><br/>
  My Component 3: <my-component3></my-component3><br/>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

<script type="text/x-template" id="my-component">
  <div >
    {{ testFunction( param1 ) }}
  </div>
</script>

  • Related