解决vue中v-html元素中标签样式失效问题

最近在项目中遇到移动端和pc端样式冲突的问题。加上scoped会导致 v-html 下绑定的标签样式不生效、第三方引用的类库对其修改也不生效,特此总结一下几点,用来解决

 

Vue为v-html中标签添加CSS样式

 1 <template>
 2  <div class="hello">
 3  <section>
 4   <h2 class="title">{{news.title}}</h2>
 5   <p class="news-time">{{news.datetime}}</p>
 6   <div class="con" v-html="news.dec">
 7   </div>
 8   <button class="back" @click="goBack()">返回列表</button>
 9  </section>
10  </div>
11 </template>

当我们使用v-html渲染页面,使用下面这种方式去修改样式并没有效果

 1 <style scoped lang="less">
 2 .con{
 3  p {
 4  font-size: 14px;
 5  line-height: 28px;
 6  text-align: left;
 7  color: rgb(238, 238, 238);
 8  color: #585858;
 9  text-indent: 2em;
10  }
11 }
12 </style>

 

 

解决方案:

当我们引入第三方组件或加载html元素时,想修改下样式,就可以用以下三种方式:

一.去掉<style scoped>中的scoped:这个方法不建议使用,会改变布局,导致组件之间样式冲突。

 

二.定义两个style标签,一个含有scoped属性,一个不含有scoped属性

 1 // 组件内
 2 <style scoped>
 3  .introduction{ 
 4  width: 100%; 
 5  margin-bottom: 3rem;
 6  }
 7 </style>
 8  
 9 // 全局
10 <style>
11  .introduction img{
12  width: 100%;
13  object-fit: fill;
14  }
15 </style> 

 

三.通过 >>> 可以使得在使用scoped属性的情况下,穿透scoped,修改其他组件的值

1 .introduction>>> img{
2  width: 100%;
3  object-fit: fill;
4 }

四.通过给各个组件的第一层标签设置唯一class或者id,使用scss,然后去掉scoped。

注意:需要严格控制class 和 id 的 根命名。保证其唯一性。

本文来自:解决vue中v-html元素中标签样式失效问题 - 建站教程 (jiuaidu.com)

posted @ 2023-03-10 17:00  强者之途  阅读(1675)  评论(0编辑  收藏  举报
/* 看板娘 */