2

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 class="badge-container" :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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.