Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you dynamically alter the CSS of a tag that's at a higher level in Vue

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading