convert string to Dom in vuejs

2019-06-23 04:22发布

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

3条回答
乱世女痞
2楼-- · 2019-06-23 04:40

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:{...}
});
查看更多
We Are One
3楼-- · 2019-06-23 04:59

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

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

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

查看更多
迷人小祖宗
4楼-- · 2019-06-23 05:01

What you are trying to do doesn't make any sense. This is not how the mustaches work. They just output strings. No wonder your output is a string.

If you want to create a new component you will need a constructor AND a DOM element, according to the following equation.

DOM el + VueComponent constructor = Vue Component

You should compose the constructor in some hook (Vue.extend), for example the created hook. Then create the element exactly like you did. Then do something like:

var myComponent = new myConstructor({el: myElement})

And voila' you're done!

查看更多
登录 后发表回答