I am working on a practice problem in Vue where I have to make a color picker and then change the background of the page to match the color that is picked. The issue is that I would need to set the background of dynamically, but I don't know how to alter the CSS of that from a component. Here's the code I have:
<!-- App.Vue -->
<script setup>
import { ColorPicker } from 'vue-accessible-color-picker';
import { ref, computed, watch } from 'vue';
const color = ref('hsl(270 100% 50% / 0.8)');
function updateColor(e) {
color.value = e.cssColor
}
const setColor = computed(() => {
return 'background: ' + color.value
})
</script>
<template>
<div :style="setColor">
<ColorPicker :color="color" @color-change="updateColor" />
</div>
</template>
Here I'm changing the style of the div within my template, but it only ever looks like this:
Not only that, but the square only ever shows up when I'm inspecting element.
When I try and change the CSS background of , I get background: var(--7a7a37b1-color) and the color doesn't change. This is when I do this for style:
<style>
html {
background: v-bind('color');
}
</style>
How do I make it so the background of the whole page changes to match the color of the color picker?
Yes, the issue with v-bind
in styles is that while the rule does apply to the outside element, the variable is only defined inside the component. So you are basically setting html.background to an empty variable.
I think this is an example where you need to set the style directly:
function updateColor(e) {
document.body.style.backgroundColor = e.cssColor
}