Jahson
Jahson

Reputation: 139

Vue is it possible to use a prop for styling? (SCSS/ SASS)

I am currently trying to allow for custom themeing of my component which uses bootstrap. I want to set its $primary tag in SCSS inside the section of the Vue component for example currently my style looks like this:

<style scoped lang="scss">
$primary: #FF1493;
// Bootstrap and its default variables
@import "../../node_modules/bootstrap/scss/bootstrap";
// BootstrapVue and its default variables
@import "../../node_modules/bootstrap-vue/src/index.scss";

@import "src/assets/custom.scss";
</style>

So I am looking for a way to have that hex code be customizable based on a prop the component recieves. Thanks for your help.

Edit after input from a comment this was attempted and did not work:

<template>
 <div style="style="{ '--test': #ff1493 }"">
 </div>
</template>

<style scoped lang="scss">
$primary: var(--test);
// Bootstrap and its default variables
@import "../../node_modules/bootstrap/scss/bootstrap";
// BootstrapVue and its default variables
@import "../../node_modules/bootstrap-vue/src/index.scss";

@import "src/assets/custom.scss";
</style>

Though leads the the following compile error in the SCSS:

SassError: argument `$color` of `darken($color, $amount)` must be a color
        on line 181 of node_modules/bootstrap/scss/_variables.scss, in function `darken`
        from line 181 of node_modules/bootstrap/scss/_variables.scss
        from line 9 of node_modules/bootstrap/scss/bootstrap.scss
        from line 201 of D:\Documents\Code\SiliconGit\src\components\SiDialog.vue

Upvotes: 2

Views: 5403

Answers (1)

Rooneyl
Rooneyl

Reputation: 7902

I tried the answer from Emad Ahmed, and it worked fine for me.
My component looks like;

<template>
    <div id="a" :style="cssVars">
        <p>Hello there</p>
    </div>
</template>

<script>
    export default {
        name: "css-change",
        props: {
            init_color: {
                required: false,
                type: String,
                default: '#ff0000'
            }
        },
        data() {
            return {
                color: this.init_color
            }
        },
        computed: {
            cssVars () {
                return{
                    /* variables you want to pass to css */
                    '--color': this.color,
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
#a{
    background-color: var(--color);
}
</style>

I am getting bootstrap imported from my package.json; "bootstrap": "4.4.1"

Upvotes: 8

Related Questions