4

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

3
  • 2
    this.template = Vue.compile('<div>{{myData}}</div>').render looks promising. source Commented Sep 12, 2019 at 7:24
  • 1
    Is there any reason to make the div not an child compontent itself? Commented Sep 12, 2019 at 7:25
  • 1
    From where is this String s coming? Commented Sep 12, 2019 at 7:26

1 Answer 1

8

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://v2.vuejs.org/v2/guide/installation.html#CLI can give more information about including the Vue Compiler.

Sign up to request clarification or add additional context in comments.

2 Comments

How to include Vue Compiler in my project
Are you using webpack? How is your project compiled? Added a link to the main post for you to read.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.