dynamically render vue template

孤街醉人 提交于 2020-07-10 10:25:30

问题


I have vue template data as string. For example,
String s = "<div>{{myData}}</div>"

And now I want to render in my already defined vue component.

<template>
<div>
   HERE I NEED TO PLACE THE STRING
</div>
</template>
<script>
export default {
  name: 'HelloWorld',
  data: {
    myData: "IRONMAN"
  },
}
</script>

Now I want the output as IRONMAN

How can i achieve this? Pleas help. Thanks


回答1:


You can have a single file component and do this - I have one called Dynamic.vue which accepts a HTML string - I use this to allow the users to generate their own templates and the bindings all match up properly, something like:

<script>
export default {
  data () {
    return {
      someVar: 'Test'
    }
  },
  props: {
    templateHtml: {
      templateHtml: true,
      type: String
    }
  },
  created () {
    this.$options.template = this.templateHtml
  }
}
</script>

If you were to call it like:

this.htmlData = '<div>Hello - {{{someVar}}</div>'
....
<my-dynamic-component :template-html="htmlData" />`

You would see the output

Hello Test

You would then omit the <template> part in the SFC.

Note: In order for this to work, you must also have the Vue Compiler included in your project (as this handles compiling the SFC into render functions which Vue uses to display data).

This link: https://vuejs.org/v2/guide/installation.html#CLI can give more information about including the Vue Compiler.



来源:https://stackoverflow.com/questions/57901607/dynamically-render-vue-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!