最近在項目中遇到移動端和pc端樣式沖突的問題。加上scoped會導致 v-html 下綁定的標簽樣式不生效、第三方引用的類庫對其修改也不生效,特此總結一下幾點,用來解決:
Vue為v-html中標簽添加CSS樣式
<template> <div class="hello"> <section> <h2 class="title">{{news.title}}</h2> <p class="news-time">{{news.datetime}}</p> <div class="con" v-html="news.dec"> </div> <button class="back" @click="goBack()">返回列表</button> </section> </div> </template>
當我們使用v-html渲染頁面,使用下面這種方式去修改樣式並沒有效果
<style scoped lang="less"> .con{ p { font-size: 14px; line-height: 28px; text-align: left; color: rgb(238, 238, 238); color: #585858; text-indent: 2em; } } </style>
解決方案:
當我們引入第三方組件或加載html元素時,想修改下樣式,就可以用以下三種方式:
一.去掉<style scoped>中的scoped:這個方法不建議使用,會改變布局,導致組件之間樣式沖突。
二.定義兩個style標簽,一個含有scoped屬性,一個不含有scoped屬性
// 組件內 <style scoped> .introduction{ width: 100%; margin-bottom: 3rem; } </style> // 全局 <style> .introduction img{ width: 100%; object-fit: fill; } </style>
三.通過 >>> 可以使得在使用scoped屬性的情況下,穿透scoped,修改其他組件的值
.introduction>>> img{ width: 100%; object-fit: fill; }
四.通過給各個組件的第一層標簽設置唯一class或者id,使用scss,然后去掉scoped。
注意:需要嚴格控制class 和 id 的 根命名。保證其唯一性。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。