admin管理员组

文章数量:1356843

see below my-ponent.vue.This Component needs to be themable.

It needs to get extrenal css sheet as i need to allow other developers to customize its inner look.

Is there any other approach than 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>

see below my-ponent.vue.This Component needs to be themable.

It needs to get extrenal css sheet as i need to allow other developers to customize its inner look.

Is there any other approach than 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>
Share Improve this question edited Jul 14, 2022 at 0:57 tony19 139k23 gold badges277 silver badges347 bronze badges asked Jul 24, 2017 at 12:38 LiranCLiranC 2,4802 gold badges30 silver badges56 bronze badges 3
  • why this approach is not good? – V. Sambor Commented Jul 24, 2017 at 12:40
  • i have experience with css in javascript from react. maybe it's ok, but it's not perfect and not intuitive to vue developers – LiranC Commented Jul 24, 2017 at 12:43
  • Don't use scoped CSS and name the classes .ponent__class. – NikxDa Commented Jul 24, 2017 at 13:20
Add a ment  | 

2 Answers 2

Reset to default 4

Inside your ponent:

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

the user could use it that way:

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


<script>

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

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

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

That way, the user can define any style he wants, to any class name he wishes. He just need to use the appropriate property name. The scoped styling has no side effects.

You can use "deep" selector to override any styles inside "scoped" ponent styles.

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

Details: vue-loader/deep-selector

本文标签: javascriptInject css to a Vue componentStack Overflow