简体   繁体   中英

Adding custom HTML element inside template using functions Vue.js

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 class="test">
    {{ testFunction(param1,param2,param3) }}
  </div>
</template>


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

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 class="test"> {{ testFunction( param1 ) }} </div> </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM