简体   繁体   中英

How can I use data from v-for list in inline css with v-bind:style?

This probably has a simple solution it's just been a while since I've used vue:

I'm trying to pass data that's pulled from a list of colors into inline css to change the background color of each item, here's an example:

<ul>
  <li v-for="color in colors">{{ color.value }}</li>
</ul>

<script>
  new Vue({
    el: '#main',
    data: {
        colors: [
            { value: '#00205b'},
            { value: '#0033a0'},
            { value: '#0084d4'}
        ],
    }
  })
</script>

I'd like to use the data pulled from color.value and place it into something like v-bind:style="background-color: { color.value }" but I can't figure out how to get this to work.

You can use like this: (See style binding )

<li v-for="color in colors" v-bind:style="{backgroundColor: color.value}">
{{ color.value }}
</li>

Or,

:style="{'background-color': color.value}"

You can create a computed property and extend each color object in the colors array with a style property. This style property will contain the styling for each element.

Finally, use the computed property in the v-for directive instead of the original array.

 new Vue({ el: '#list', data() { return { colors: [{ value: '#00205b' }, { value: '#0033a0' }, { value: '#0084d4' } ], }; }, computed: { extendedColors() { return this.colors.map(color => ({ ...color, style: { backgroundColor: color.value } })); }, } })
 <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script> <ul id="list"> <li v-for="color in extendedColors" :style="color.style"> {{ color.value }} </li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM