javascript - vue converts string to html
为情所困
为情所困 2017-05-19 10:31:46
0
5
798
let str = "<img :src=('face[k].src)>"
this.commentList[i].Content = this.commentList[i].Content.replace(sArr[j], str)

The requirement is to convert the string in str into html output. This img is an expression. Check whether the returned content contains an expression, and then replace it. If I output it like this, it is just a string. How can I convert it to html? ? It seems that the eval() method is not supported

为情所困
为情所困

reply all(5)
phpcn_u1582

As follows, after obtaining the data, you should modify the Content to html and bind it using the v-html command:

<template>
    <ul v-for="item in commentList">
        <li>
            <p v-html='item.Content'></p>
        </li>
    </ul>
</template>

<script>
    export {
        data() {
            return {
                commentList: []
            }
        },
        created() {
            this.$http.get('api/get-commentlist?article_id=1').then((res) => {
                res = res.body
                res.list.forEach((item, i) => {
                    // sdfsafs[face-1]sad[face-2] 
                    // 将被替换为 
                    // sdfsafs<img src="face-1.jpg">sad<img src="face-2.jpg">
                    // ,请自行根据需要修改
                    item.Content = item.Content.replace(/\[face\-(\d+)\]/g, '<img src="face-.jpg">')
                })
                this.commentList = res.list
            })
        }
    }
</script>

--- Supplement ---

The second parameter of the .replace() method also supports the use of function returns, which can achieve more complex replacements, such as:

item.Content = item.Content.replace(/\[(.+)\]/g, function(word, ){
  return '<img src="/static/img/'+ this.face[].src +'" />'
})
曾经蜡笔没有小新

v-html?

Peter_Zhu

It is recommended to use v-ifBetter

迷茫

Use innerHTML for native, html() for jq;

大家讲道理

Has anyone encountered the same problem~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!