Search code examples
javascriptimagevue.jsvuejs2vue-component

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>


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>