3

How can I use data() values in <style>..</style>? I tried several combinations (with/without this, with/without {{brackets}} etc. but can't get it to work. If I enter a value like '#f00' instead it works fine.

I built a template like so:

<template>
 <ul class="striped">
     <li>foo</li>
     <li>bar</li>
     <li>foobar</li>
</ul>


</template>

<style>
 ul.striped> li:nth-of-type(odd) {
    background-color: this.colors[0].backgroundcolor;  //dynamic value from data()
}
</style>

<script>

  data() {
    return {

        colors: [{'backgroundcolor':'#def'}], //simplified version for explanation
[..]
</script>

1 Answer 1

3

With the Vue 3.2 release you can just use State-Driven Dynamic CSS like that :

<template>
    <ul class="striped">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: v-bind('colors[0]')
    }
</style>

<script>
    data() {
        return {
            colors: ['#def'],
        }
    }
</script>

If you're using Vue 2 you may use CSS custom properties like that :

<template>
    <ul class="striped" :style="`--color: ${colors[0]}`">
        <li>foo</li>
        <li>bar</li>
        <li>foobar</li>
    </ul>
</template>

<style>
    ul.striped> li:nth-of-type(odd) {
        background-color: var(--color)
    }
</style>

<script>
   export default {
      data() {
        return {
            colors: ['#def'],
        }
    }
   }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice, thank you for both versions, works like a charm.

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.