javascript - vue將字串轉為html
为情所困
为情所困 2017-05-19 10:31:46
0
5
762
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()方法好像不支援

为情所困
为情所困

全部回覆(5)
phpcn_u1582

如下,應該在取得到資料之後修正 Content 為 html, 並使用 v-html 指令綁定:

<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>

--- 補充 ---

其中 .replace() 方法的第二個參數也支援使用函數返回,即能實現更複雜的替換,如:

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

v-html?

Peter_Zhu

建議使用v-if更好

迷茫

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

大家讲道理

沒有人遇到同樣的問題嗎~

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!