Home > database >  How to make anchor links inside v-html work in Vue.js?
How to make anchor links inside v-html work in Vue.js?

Time:12-06

I need to create user guide pages using v-html, and inside the pages there should be anchor links. However, the following does not work within v-html:

<a href="#foobar">
...
<a id="foobar">

Is there a way to fix this in Vue 2?

CodePudding user response:

Try this code.

  <div v-html="msg"></div>
  <div style="margin-top:2000px;"></div>

  <div id="foobar">
    Tet
  </div>

new Vue({
  el: '#app',
  data: {
    msg: '<a href="#foobar">Footer</a>'
  }
})

https://codepen.io/Pratik__007/pen/LYrMbzd

CodePudding user response:

It should work fine. I just created a working demo below. Please have a look. I hope it will help you in finding the root cause of the issue you are facing.

new Vue({
  el: '#app',
  data: {
    pageData: `<a href="#foobar">Scroll to Footer!</a><br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              ...<br>
              <div id="foobar">
                Footer
              </div>`
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-html="pageData"></div>
</div>

  • Related