VUE3 Color Picker for CSS Root Vars

Home Code VUE3 Color Picker for CSS Root Vars

This component is used in the website's heading. When you click one of the buttons, a set of RGB values are ran through a method (pickColor) which sets two style properties: a regular one, and one with transparancy added for duotone rendering.

Vue3 Component

This component is used on our homepage. When you click one of the buttons, a set of RGB values are ran through a method (pickColor) which sets two style properties: a regular one, and one with 0.5 transparancy added for duotone rendering.

                            app.component('color-picker',
{
    name:"Color Picker",
    props:{
        colors:{
            type:Array,default:[
                {r:255,g:255,b:255},
                {r:255,g:255,b:255},
                {r:255,g:255,b:255},
                {r:255,g:255,b:255}
            ]
         },
    },
    data(){
        return{
            picked:{'r':0,'g':0,'b':0}
        }
    },
    methods:{
        pickColor:function(r, g, b){
            this.picked = {r:r, g:g, b:b};
            this.setStyles();
        },
        setStyles:function()
        {
            document.documentElement.style.setProperty('--color-heading', this.rgb);
            document.documentElement.style.setProperty('--color-duotone', this.rgba);
            localStorage.setItem("picked", JSON.stringify(this.picked));
        }
    },
    computed: {
        rgb () { return "rgb(" + this.picked.r + "," + this.picked.g + "," + this.picked.b + ")"; },
        rgba () { return "rgb(" + this.picked.r + "," + this.picked.g + "," + this.picked.b + "," + "0.5" + ")"; }
    },
    mounted(){
        let pickedColor = localStorage.getItem("picked");
        if (pickedColor) {
            this.picked = JSON.parse(pickedColor);
            this.setStyles();
        }
    },
    template:
    `
    <div class="colorpicker">
        <div v-for="color in colors" class="square" v-on:click="pickColor(color.r, color.g, color.b)" :style="{backgroundColor:'rgb('+color.r+','+color.g+','+color.b+')'}"></div>
    </div>
    `
});                        

HTML Implementation

Simply pass an array of RGB value objects to the component using a Prop.

                            <color-picker :colors="[{r:155,g:155,b:255},{r:0,g:155,b:155},{r:155,g:155,b:155},{r:0,g:0,b:0}]"></color-picker>                        

Tech Stack

PHP

HTML

Javascript

C#

CSS