Reputation: 323
In Angular we can dynamically set css properties, like this:
<style ng-if="color">
.theme-color { color: {{color}}; }
.theme-background-color { background-color: {{color}}; }
.theme-border-color { border-color: {{color}}; }
</style>
In Vue, we can modify :class=... but that limits us to predefined class options, and :style... that doesn't allow us to use class names.
Is there a way to achieve dynamic CSS as above? Or do we have to code the styles so that they include all color properties?
Thanks
Upvotes: 3
Views: 1333
Reputation: 440
Assuming this has some sort of user colour picking intervention; I would store the user's chosen colour in the state, so it's globally accessible.
Then within your component, you could do the following...
<app :style="themeStyles"></app>
export default {
computed: {
themeStyles () {
return {
color: store.state.themeColor,
backgroundColor: store.state.themeColor,
borderColor: store.state.themeColor
}
}
}
}
(Pseudocode so to provide example quickly)
Obviously, use it on whatever component you need - but it should do the trick, so long as you have a way of storing user's input for the themeColor itself & store it in the state.
Edit: additional option
Upvotes: 2
Reputation: 32921
If you don't need Internet Explorer support you can use CSS variables.
Here's a quick CodeSandbox with an example: https://codesandbox.io/s/rr80o6kq3n
Here's the relevant code.
<template>
<div class="foo">
<div class="bar">Hello World</div>
</div>
</template>
<style scoped>
.foo {
--theme-color: black;
}
.bar {
font-weight: bold;
transition: color 0.2s;
color: var(--theme-color);
}
</style>
<script>
export default {
data () {
return {
hue: 0,
}
},
watch: {
hue (hue) {
this.$el.style.setProperty(
"--theme-color",
`hsl(${hue % 360}, 100%, 50%)`,
)
},
},
mounted() {
window.setInterval(() => {
this.hue += 20
}, 500)
},
}
</script>
Upvotes: 1