首页 > 解决方案 > 如何更改 v-for 循环 vuejs 中项目的背景?

问题描述

我有这个数组

      items: [
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
        },
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
        },
]

我想为这些项目中的每一个提供特定的背景,我该怎么做?

这是我的v-for循环代码:

<div v-for="(item, index) in items">
    <div :style="whatShouldIGiveItHere">
        {{item}}
    </div>
</div>

编辑:我试图用这个添加变体背景颜色,computed但它不起作用:

colorVariant() {
  const colorVar = ['red', 'blue', 'green']
  colorVar.forEach((val) => {
    return val
  })
},


<div v-for="(item, index) in items">
    <div :style="background:colorVariant">
        {{item}}
    </div>
</div>

标签: vue.js

解决方案


要为每张卡片添加不同的背景颜色,您可以在 items 数组中添加一个属性。

items: [
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
          bgColor: 'red',

        },
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
          bgColor: 'green',
        },
]

循环时添加这样的样式

<div v-for="(item, index) in items">
    <div :style="`background-color: ${item.bgColor}`">
        {{item}}
    </div>
</div>

// 编辑 - 需要项目数组之外的背景颜色(虽然不是一个好方法)

bgColors: ['red', 'green'],
items: [
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
        },
        {
          cardTitle: 'Mathew Slick attached 2 files',
          dateTime: '15 min ago',
          contentTitle: 'Article / Post',
          contentValue:
            'The history of video game is as interesting as a fairy tale. The quality of today’s video game was not at all there when',
        },
]
/* the loop will take the same index color and add it to the card. */
<div v-for="(item, index) in items">
    <div :style="`background-color: ${bgColors[index]}`">
        {{item}}
    </div>
</div>

推荐阅读