21

recently I want to convert a stirng to Dom in a vue component, but it does't work as my expectation. My code looks like this:

  // what I wrote in the template
  <div id="log">
      {{libText}}
  </div>

  // what I wrote in js
        Vue.component(...  , {
        template: ...  ,
        data: function () {
               return ...     
            }
        },
        computed: {           
            libText:function(){
                var str="<p>some html</p>";
                var div = document.createElement('div');
                div.innerHTML = str;
                return div;
            }
        },
        methods:{...}
        })

The result I get is a string "[object HTMLDivElement]" rather than a Dom. It would be greatful if anyone can help me solve this problem

2 Answers 2

60

If you are using Vue 2, use the v-html directive:

<div v-html="yourVariable"></div>

https://v2.vuejs.org/v2/api/#v-html

Sign up to request clarification or add additional context in comments.

2 Comments

It works perfectly even if you want to leave it as string. Thanks!
worked on Vue 3 too, thanks!
7

A possible solution is:

Template:

<div id="log">
    {{{libText}}}
</div>

Notice triple {} for get raw html/text interpretation.

Javascript:

Vue.component(...  , {
    template: ...  ,
    data: function () {
           return ...     
        }
    },
    computed: {           
        libText:function(){
            // return directly html
            var str="<div><p>some html</p></div>";
            return str;
        }
    },
    methods:{...}
});

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.