Vue 使用篇(三):scoped屬性的style樣式如何應用於其子組件中

1、問題描述

爲了保證樣式只應用於當前組件,咱們在<style>標籤上添加scoped屬性,然而若是咱們運用了v-html設置頁面的內容,則組件的樣式沒法滲透到v-html設置的內容中。html

<template>
  <div>
    <div class='demo' v-html="htmlCode"></div>
    <p>this is main content</p>
  </div>
</template>

<script>
export default {
  name: 'demo',
  data () {
    return {
      htmlCode: '<p>this is v-html content</p>'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
p {
  /* 對v-html中的內容無效 */
  color: red;
}
</style>
複製代碼

2、解決方案

一、經過所有樣式

使用全局樣式可以將樣式做用於全局的所有元素bash

<style>
p {
  color: red;
}
複製代碼

二、使用深度做用選擇器

可是若是我不想讓這些組件的樣式「污染」到了全局的樣式,只想將這些樣式做用於這個組件內部,那麼爲了讓scoped的樣式可以做用得「更深」,從而影響子組件,此時能夠使用深度做用選擇器,即便用 >>> 操做符ui

<style scoped>
/* 對v-html中的內容無效 */
p {
  color: red;
}

/* 做用於子組件中 */
.demo >>> p{ 
  color: blue;
}
</style>
複製代碼
相關文章
相關標籤/搜索