用v-html 设定类样式如何生效

920 阅读1分钟
<div class="concern-item" v-if="concernTextList[0]!=''" >
  <span class="concern-value-text" v-html="concernTextList[0]"></span>
</div>

一、样式生效

txt_5=`<span  style='color:#FF6A17; font-weight: bold;'>${data.result[0].TXT_5}</span>`
this.concernTextList[0]=`${txt_5}`    

二、样式不生效

txt_5=`<span  class="red">${data.result[0].TXT_5}</span>`
this.concernTextList[0]=`${txt_5}`    
<style scoped lang="less">
 .red{
    color:#FF6A17; font-weight: bold;
  }
</style>

不生效原因:

scoped属性导致css仅对当前组件生效,v-html绑定渲染出的内容可以理解为是子组件的内容,子组件不会被加上对应的属性,所以不会应用CSS.

解决办法:

 1 、less sass

<style scoped lang="less">.concern-item/deep/.red{ color:#FF6A17; font-weight: bold;

2、或者是使用stylus编译器

<style scoped lang="less">
  .concern-item>>>.red{
    color:#FF6A17; font-weight: bold;
  }
</style>

 3、去掉scoped

<style  lang="less">
 .red{
    color:#FF6A17; font-weight: bold;
  }
</style>