Search code examples
cssvue.jsstyles

VueJS: use data value in style


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>

Solution

  • 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>