【问题标题】:Inject css to a Vue component?将 css 注入 Vue 组件?
【发布时间】:2017-12-30 01:19:49
【问题描述】:

见下文my-component.vue。此组件需要可主题化。

它需要获取外部 css 表,因为我需要允许其他开发人员自定义其内部外观。

除了accept a javascript object还有其他方法吗?

<template>
  <div class="container">
    <div class="A"></div>
    <div class="B"></div>
    <div class="C"></div>
  </div>
</template>

<style scoped>
  .A {
    background-color:green;
  }
  .B {
    background-color: red;
  }
  .C {
    background-color: yellow
  }
</style>

【问题讨论】:

  • 为什么这种方法不好?
  • 我有来自 react 的 JavaScript 中的 css 经验。也许没问题,但它并不完美,对 vue 开发人员来说也不直观
  • 不要使用作用域 CSS 并将类命名为 .component__class。

标签: javascript css vue.js


【解决方案1】:

在你的组件内部:

<template>
  <div :class="boxStyle"></div>
</template>

<script>
  export default {
    props: {
      boxStyle: {
        type: String,
        default: 'box-default'
      }
    }
  }
</script>

<style lang="scss" scoped>
.box-default {
  width: 100px;
  height: 100px;
  background: black;
}
</style>

用户可以这样使用它:

<template>
  <div id="app">
    <my :boxStyle="'mySpecialBox'"></my>
  </div>
</template>


<script>

import myCompoentns from './components/myComponent.vue'

export default {
  name: 'app',
  components: {
    'my': myCompoentns
  },
}
</script>

<style lang="scss">
  .mySpecialBox {
    width: 250px;
    height: 250px;
    background: red;
  }
</style>

这样,用户可以定义任何他想要的样式,任何他想要的类名。他只需要使用适当的属性名称。 作用域样式没有副作用。

【讨论】:

    【解决方案2】:

    您可以使用“深度”选择器覆盖“范围”组件样式中的任何样式。

    <style scoped>
    .a >>> .b { /* ... */ }
    </style>
    

    详情:vue-loader/deep-selector

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2019-11-03
      • 2021-09-12
      • 2018-07-28
      • 2021-11-30
      • 2019-03-06
      • 1970-01-01
      • 2021-01-30
      • 2022-08-15
      相关资源
      最近更新 更多