Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 447
LiranC Avatar asked Jul 24 '17 12:07

LiranC


1 Answers

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.

like image 188
Avi Waserman Avatar answered Sep 18 '22 00:09

Avi Waserman