简体   繁体   English

使用函数 Vue.js 在模板中添加自定义 HTML 元素

[英]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?有什么方法可以使用 javascript 函数在模板标签内渲染带有自定义属性的 html 元素吗?

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直接你会得到插值 html,就像这样

<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.即使您使用v-html指令将其修复为 output raw HTML按钮仍然无法使用。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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