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

发布时间:2019-05-26 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[分享][Vue踩坑记]scoped CSS脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

what's scoped CSS ?

当 <style> 标签有 scoped 属性时,它的 CSS 只作用于当前组件中的元素。

场景一:

在 scoped CSS 下 改不动样式!!!

例: (我们尝试修改 element-ui 的 input 组件的样式并只在 app.vue 下生效)

ok...拿起键盘...

<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>

嗖嗖一顿敲...

满怀期待的看向浏览器...

WC.. 没效果???

原因:

使用 scoped 后,父组件的样式将不会渗透到子组件中。

解决方法:

使用深度作用选择器 /deep/

<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

脚本宝典总结

以上是脚本宝典为你收集整理的[分享][Vue踩坑记]scoped CSS全部内容,希望文章能够帮你解决[分享][Vue踩坑记]scoped CSS所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:CSSVue