Home  >  Q&A  >  body text

javascript - vue converts string to html

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

为情所困为情所困2699 days ago760

reply all(5)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:33:46

    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 +'" />'
    })

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:33:46

    v-html?

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:33:46

    It is recommended to use v-ifBetter

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:33:46

    Use innerHTML for native, html() for jq;

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:33:46

    Has anyone encountered the same problem~

    reply
    0
  • Cancelreply