Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to interpret html in an attribute with Vue

I need to convert some code to Vue, I have a rendering difference in the alt attribute of an image, because I can’t find a way to interpret the html in the attributes, I haven’t found any topics that talk about this do you have an idea please?

In the examples I made on purpose not to put src to see the alternative texts.

Vue.component('first-image', {
  inheritAttrs: false,
  template: '<div class="container-image"><img v-bind="$attrs"></div>'
});

Vue.component('second-image', {
  template: '<img>',
});

new Vue({
  el: '#app',
  data() {
    return {
       alternativeText: '1&nbsp;000€',
    };
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<!-- Without VueJS -->
<img alt="1&nbsp;000€">

<br>
<br>

<!-- With VueJS -->
<div id="app">
  <first-image :alt="alternativeText"></first-image>
  <second-image alt="1&nbsp;000€"></second-image>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try like following snippet:

Vue.component('first-image', {
  inheritAttrs: false,
  template: '<div class="container-image"><img v-bind="$attrs"></div>'
});

Vue.component('second-image', {
  template: '<img>',
});

new Vue({
  el: '#app',
  data() {
    return {
       alternativeText: '1&nbsp;000€',
    };
  },
  methods: {
    decodeHtml(html) {
      const txt = document.createElement("textarea");
      txt.innerHTML = html;
      return txt.value;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<!-- Without VueJS -->
<img alt="1&nbsp;000€">

<br>
<br>

<!-- With VueJS -->
<div id="app">
  <first-image :alt="decodeHtml(alternativeText)"></first-image>
  <second-image alt="1&nbsp;000€"></second-image>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading