v-html 样式无效,图片不显示

代码模拟:

<template>
  <article>
    <div>content1:接口返回</div>
    <div class="content" v-html="content1"></div>
    <div>content2:前端代码</div>
    <div class="content" v-html="content2"></div>
  </article>
</template>

<script>

export default {
  data() {
    return {
      content1: "<div style=\"color:#333;font-size:14px;\">测试数据哈哈哈 <span style=\"color:#1188ff;font-weight:600;\">蓝色加粗</span><span style=\"font-weight:600;\">-黑色加粗</span> 感谢您的支持。</div><img src=\"https://www.baidu.com/img/flexible/logo/pc/result.png\" style=\"margin-top:20px;\" />",
      content2: "<div style=\"color:#333;font-size:14px;\">测试数据哈哈哈 <span style=\"color:#1188ff;font-weight:600;\">蓝色加粗</span><span style=\"font-weight:600;\">-黑色加粗</span> 感谢您的支持。</div><img src=\"https://www.baidu.com/img/flexible/logo/pc/result.png\" style=\"margin-top:20px;\" />",
    };
  },
};
</script>

<style lang="scss">
</style>
// 

展示效果和渲染代码,如下图所示:前端使用 v-html 解析时,发现接口返回的代码(content1)样式不起作用,而且图片也没解析处理;而前端写的代码块(content2)是可以解析出来的。查看源码可以看出,content1的代码渲染错误了。
在这里插入图片描述
在这里插入图片描述

原因分析:肉眼看来,这两个数据是完全一样的,但是实际是有区别的,用比对工具查看,可看出空格是不一样的,接口返回的空格是&nbsp,如下图所示:
在这里插入图片描述

v-html样式无效时,可使用::v-deep进行样式覆盖

<template>
   <div class="content" v-html="content3"></div>
</template>

<script>
export default {
  data() {
    return {
      content3: "测试数据哈哈哈 <span class=\"first\">蓝色加粗</span><span class=\"second\">-黑色加粗</span> 感谢您的支持。<img src=\"https://www.baidu.com/img/flexible/logo/pc/result.png\" class=\"icon\" />",
  },
};
</script>

<style lang="scss" scoped>
.content {
  ::v-deep .first {
    font-weight: bold;
    color: #1188ff;
  }
  ::v-deep .second {
    font-weight: bold;
  }
  ::v-deep .icon {
    width: 100%;
    margin-top: 20px;
    border: 1px solid red;
  }
}
</style>

效果查看:
在这里插入图片描述


版权声明:本文为gaoxiaoba原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。