vue将字符串转为为html

let str = "<img :src=('face[k].src)>"
this.commentList[i].Content = this.commentList[i].Content.replace(sArr[j], str)

需求是将str里面的字符串转成成html输出,这个img是表情来的,检测返回content中是否包含表情,然后替换,如果我这样输出的话只是字符串,请问如何转化为html呢?用eval()方法好像不支持

阅读 16.4k
6 个回答

如下,应该在获取到数据之后修正 Content 为 html, 并使用 v-html 指令绑定:

<template>
    <ul v-for="item in commentList">
        <li>
            <div v-html='item.Content'></div>
        </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-$1.jpg">')
                })
                this.commentList = res.list
            })
        }
    }
</script>

--- 补充 ---

其中 .replace() 方法的第二个参数也支持使用函数返回,即能实现更复杂的替换,如:

item.Content = item.Content.replace(/\[(.+)\]/g, function(word, $1){
  return '<img src="/static/img/'+ this.face[$1].src +'" />'
})

建议使用v-if更好点

原生的用innerHTML,jq用html();

补充一下推荐答案的回答,如果这样的字符串
"hello[smile]world[cry]!"
推荐答案的正则匹配出来是[smile]world[cry]
正解:\[([^\]]+)\]
匹配:[smile],[cry]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题