4

I'm working on a component in VueJs and I want to make a color attribute that take hexadecimal color and convert into rgb color with rgba function of sass and work with it.

props: {
    color: {
        type: String,
        default: '#195cff'
    }
}

I tried to do it like this:

$color: v-bind(color);

input {
    background: rgba($color, 0.5);
}

But I think v-bind is not accessible in sass variable. How can I do this work.

2
  • 1
    You can't make it work. SASS variables don't exist at the time when the app runs. You could use CSS variables for that. You may want to not make it harder and just apply colors directly to style Commented Jun 17, 2022 at 6:05
  • 1
    Use class bindings. Or, Have the color supplied from vue properties instead of sass variables Commented Jun 17, 2022 at 6:49

1 Answer 1

3

That's strictly impossible but I found a way to have a similar result.

props: {
        color: {
            type: String,
            default: '#195cff',
        },
    },
    methods: {
        hexToRgb(hex) {
            let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            return result ? {
                r: parseInt(result[1], 16),
                g: parseInt(result[2], 16),
                b: parseInt(result[3], 16)
            } : null;
        }
    },
    data: function () {
        return {
            rgbColor: `${this.hexToRgb(this.color).r},${this.hexToRgb(this.color).g},${this.hexToRgb(this.color).b}`
        }
    }

And in css

input {
    background: rgb(v-bind(rgbColor),0.5);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Except it is allowed by Vue via v-bind(): vuejs.org/api/sfc-css-features.html#v-bind-in-css

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.