2

I'm new to Vue.js

I want to render a script tag inside a variable (data string).

I tried to us a v-html directive to do so, but it doesn't work Nothing is rendered

Any way I can achieve this?

2
  • I dont fully understand your question. Do you mean you have a string variable that contains html/javascript that you want to render inside another html tag? Commented Oct 16, 2018 at 15:51
  • 1
    You cannot create a parsed <script> tag through innerHTML (which is what v-html would be doing). Can scripts be inserted with innerHTML?. Commented Oct 17, 2018 at 14:21

3 Answers 3

1

I'd place a v-if directive on the script tag and put the content of it in a variable.

<script v-if="script">
  {{script}}
</scrip>
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand you correctly, my answer is:

<template>
  <div>
    {{ strWithScriptTag }}
  </div>
</template>

<script>
export default {
   name: 'Example',

   methods: {
     htmlDecode(input) {
       const e = document.createElement('div')
       e.innerHTML = input
       return e.childNodes[0].nodeValue
     },
   },


  computed: {
     strWithScriptTag() {
       const scriptStr = '&lt;script&gt;https://some.domain.namet&lt;/script&gt;'
       return this.htmlDecode(scriptStr)
     }
   },
}
</script>

1 Comment

You can also use lodash's unescape instead htmlDecode(input).
0

I think that by safety vue is escaping your <script> automatically and there is no way to avoid this.

Anyway, one thing you can do is eval(this.property) on created() lifecycle hook.

data: {
  script: 'alert("this alert will be shown when the component is created")'
},
created() {
  eval(this.script)
}

Use it with caution, as stated in vue js docs, this may open XSS attacks in your app

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.