cwj
cwj

Reputation: 2583

Setting dynamic global styles programmatically in Vue

I have a Vue component that needs to control the background color of the entire page dynamically. It has an internal state, and that state has the side-effect of causing the background of the page to change.

Ordinarily at the component level this would be accomplished by using v-bind in CSS:

<style lang="scss">
.some-class {
  background-color: v-bind("some.variable");
}
</style>

This will work and the component's background will become the color defined in some.variable.

However, trying to use v-bind on :root (or anything outside of the component's scope) will fail. i.e.:

<style lang="scss">
html {
  background-color: v-bind("some.variable");
}
</style>

… will not set the CSS property correctly. This is because the variable is declared at the component level. i.e.:

CSS:

html {
  background-color: var(--something)
}

HTML:

<html>
  <div style="--something">
</html>

What is therefore the "correct" or suggested practice? Do I manage it as a side-effect with watchers? Is there a flag to pass to v-bind?

Upvotes: 4

Views: 967

Answers (1)

Duannx
Duannx

Reputation: 8726

The best practice really depends on what is your goal.

If you want to set the background for your app only (maybe not the entry document), you can put your code inside the App.vue component. Now your variable will take the root scope of your app and apply to any class that is inside the #app element.

If you have to set the background for the body or html element, you have no choice but to use a watcher. The code is something like that:

watch(someVariable, ()=>{
  document.body.style.setProperty('--background-color', someVariable.value);
})

Upvotes: 3

Related Questions