后端返回这么一段字符串模板,前端怎么解析?

let data={
           title:'标题',
           content:'内容',
           list:[
             { text:'1111', status:true },
             { text:'2222', status:false},
             { text:'3333', status:true },
             { text:'4444', status:false}
           ]
        }
        let temp=`<div>
             <h3 style="font-size:20px; color:red">${data.title}</h3>
             <div style="font-size:15px; color:blue">${data.content}</div>
             <ul>
                ${data.list.map(item=>{ 
                  if(item.status){
                     return `<li style="color:red">${item.text}</li>`
                  }else{
                     return `<li style="color:black">${item.text}</li>` 
                  }
                }).join('')}
             </ul>
          </div>`
          console.log(temp)
          

打印html代码

<div>
           <h3 style="font-size:20px; color:red">标题</h3>
           <div style="font-size:15px; color:blue">内容</div>
           <ul>
              <li style="color:red">1111</li><li style="color:black">2222</li><li style="color:red">3333</li><li style="color:black">4444</li>
           </ul>
        </div>

现在temp通过接口返回获取,这个时候该如何编译才能正常显示

阅读 3.3k
2 个回答

你可以看下demo,可以实现但是安全性会有问题,建议最好是不要这样来处理,可以考虑处理一下返回的模板用 compile 来实现。 API — Vue.js

<template>
  <div id="app">
    <div v-html="template"></div>
  </div>
</template>

<script>
let temp="<div><h3 style='font-size:20px; color:red'>${data.title}</h3><div style='font-size:15px; color:blue'>${data.content}</div><ul>${data.list.map(item=>{ if(item.status){ return `<li style='color:red'>${item.text}</li>` }else{ return `<li style='color:black'>${item.text}</li>` }}).join('')}</ul></div>"

export default {
  name: 'App',
  data(){
    return{
      data:{
        title:'标题',
        content:'内容',
        list:[
          { text:'1111', status:true },
          { text:'2222', status:false},
          { text:'3333', status:true },
          { text:'4444', status:false}
        ]
      },
      template:""
    }
  },
  mounted(){
    this.template = this.test(this.data,temp)
  },
  methods:{
    test(data,temp){
      return new Function("data",`return \`${temp}\`;`)(data)
    }
  }
}
</script>

image.png


已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入。

在vue中可以使用v-html指令

<div v-html='temp'></div>

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