Answer a question

In my case, I am replacing a link on top of paragraph element using v-html

Please find the code snippet as follows

 <p v-html="websiteHTML"></p>

where websiteHTML contains: <a v-bind:href="google.com/">Google</a>

The <p> tag is being rendered with Google but doesn't have hyperlink to navigate to https://www.google.com/

Could you please help in finding the error?

Answers

The HTML string you include in your variable should just be HTML, not Vue template code. When you tried including vue template directives, the framework wrote the anchor tag into the DOM with the literal attribute "v-bind:href" instead of the desired "href":

new Vue({
  el: '#app',
  data: {
    websiteHTMLNo: '<a v-bind:href="https://google.com/">Google</a>', // <-- won't work
    websiteHTMLYes: '<a href="https://google.com/">Google</a>'  // <-- do this instead
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p v-html="websiteHTMLNo"></p>
  <p v-html="websiteHTMLYes"></p>
</div>

(If you actually do need to inject template code instead of plain HTML, you need to use Vue.compile instead of v-html to parse it.)

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐