使用 v-for 循环绑定不同颜色的背景

Binding different color backgrounds using v-for loop

我正在使用 vuetify 并尝试遍历 javascript 对象,其中包含我想应用为背景的不同十六进制代码。

最终结果看起来像这样:

我正在尝试将每个 Hexcode 绑定到每个不同项目颜色的背景。

以下是我尝试做事的方式:

<!-- Color Cards -->
           <v-container grid-list-md text-xs-center>
              <v-layout row wrap>
                <v-flex class="item" xs12 sm4 v-for="color in colors" :key="color.id">
                  <v-card  ripple hover class="">
                    <div  class="item-color"
                          v-for="(hex, index) in colors.hex"
                          :key="index"
                          :style="{ 'background-color': hex[index]}">
                    </div>
                    <v-card-text class="px-0">{{ color.title }}</v-card-text>
                  </v-card>
                </v-flex>
              </v-layout>
            </v-container>

这是数据对象:

export default {
      data () {
        return {
            colors: [
            {
              id: 'ssmf',
              hex: ['#297afb','#2898fb','#01d8fd'],
              title: 'Sleek, Sophisticated, Mature & Formal'
            },
            {
              id: 'hlfss',
              hex: ['#297afb','#2898fb','#01d8fd'],
              title: 'Honest, Loyal, Friendly, Stable, & Strong'
            }
            ]
        }
      }
  }

有两个错误:

  1. <v-flex> 中,您正在使用 v-for="color in colors" 进行迭代,因此 color 是在 colors 数组中迭代的数组项的别名。但是在 v-card> 元素的 div 标记中,您正在迭代 colors.hex。所以应该是 v-for="(hex, index) in color.hex" 而不是 colors.hex
  2. hex 是在 color.hex 中迭代的项目,它是一个字符串。所以你可以直接使用它,不需要hex[index]

    <v-container grid-list-md text-xs-center>
      <v-layout row wrap>
        <v-flex class="item" xs12 sm4 v-for="color in colors" :key="color.id">
          <v-card  ripple hover class="">
            <div  class="item-color"
                  v-for="(hex, index) in color.hex"
                  :key="index"
                  :style="{ 'background-color': hex}">
            </div>
            <v-card-text class="px-0">{{ color.title }}</v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
    

稍微更改 v-for 循环,因为您已经在 color.hex 上迭代,所以您需要参考的只是十六进制。

<div v-for="color in colors">
    <div  class="item-color"
          v-for="(hex, index) in color.hex"
          :key="index"
          :style="{ 'background-color': hex}">
   </div>
</div>

这是一个有效的 fiddle https://jsfiddle.net/skribe/00cf8z7x/4/

如果您希望语法易于阅读,请将对象中的 hex 更改为 hexs

colors: [
        {
          id: 'ssmf',
          hexs: ['#297afb','#2898fb','#01d8fd'],
          title: 'Sleek, Sophisticated, Mature & Formal'
        },
   ....

然后你可以把你的v-for写成v-for="hex in color.hexs"