LiranC
LiranC

Reputation: 2480

Inject css to a Vue component?

see below my-component.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>

Upvotes: 8

Views: 7531

Answers (2)

vovchisko
vovchisko

Reputation: 2239

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

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

Details: vue-loader/deep-selector

Upvotes: 1

Avi Waserman
Avi Waserman

Reputation: 96

Inside your component:

<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 './components/myComponent.vue'

export default {
  name: 'app',
  components: {
    '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.

Upvotes: 4

Related Questions