Dynamically Styled Component
I'm trying to create dynamically styled component, by setting CSS values from JavaScript variables without using Document Web API's, I mean methods like Document.getElementById()
&
Document.querySelector()
.
I'm using Vue.JS btw, And I came up with a code that looks like this:
<template>
<div :style="myStyle">
<slot></slot>
</div>
<template>
<script>
setup(props) {
const myStyle = ref(`--color: ${props.color}`)
return{myStyle}
}
</script>
<style>
.badge-container::after {
background-color: var(--color);
}
</style>
It works fine, but only for one variable, & I want to use multiple variables, how do I pass multiple variables to CSS from JS.
I've tried to convert myStyle to an object to pass multiple values but I've failed.
I could put all the style like this <div :style="color: ${color}">
but the problem in this way that the div style will changed and I want to change ::after .badge-container::after
Is there anyway to make this happen, without using Document Web API's Or JSX.
CodePudding user response:
You can use this feature of Vue3: v-bind-in-css
So that you can get a fully dynamic styling based on actual state
<script setup>
const theme = {
color: 'red'
}
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
color: v-bind('theme.color');
}
</style>
As shown here in this playground.