[分享][Vue踩坑記]scoped CSS

what's scoped CSS ?

當 <style> 標籤有 scoped 屬性時,它的 CSS 只做用於當前組件中的元素。javascript

場景一:

在 scoped CSS 下 改不動樣式!!!css

例: (咱們嘗試修改 element-ui 的 input 組件的樣式並只在 app.vue 下生效)html

ok...拿起鍵盤...vue

<template>
  <div id="app">
    <el-input  class="text-box" v-model="text"></el-input>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      text: 'hello'
    };
  }
};
</script>

<style lang="less" scoped>
.text-box {
   input {
    width: 166px;
    text-align: center;
  }
}
</style>

嗖嗖一頓敲...java

滿懷期待的看向瀏覽器...git

WC.. 沒效果???github

緣由:

使用 scoped 後,父組件的樣式將不會滲透到子組件中。web

解決方法:

使用深度做用選擇器 /deep/element-ui

<template>
  <div id="app">
    <el-input v-model="text" class="text-box"></el-input>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      text: 'hello'
    };
  }
};
</script>

<style lang="less" scoped>
.text-box {
  /deep/ input {
    width: 166px;
    text-align: center;
  }
}
</style>

大功告成瀏覽器

場景二:

動態生成的DOM類名樣式不做用!

解決方法:

<template>
  <div id="app">
    <div v-html="text"></div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      text: '<span class="red">紅色<span>'
    };
  }
};
</script>

<style lang="less" scoped>
/deep/ .red {
  color: #f33;
}
</style>

參考文檔

以後會持續分享在Vue中遇到的一些坑哈~

若是有幫助到你,請給我 star

相關文章
相關標籤/搜索