[分享][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

相关文章
相关标签/搜索