如何在Prop for for loop中传递背景色?

时间:2019-07-07 19:35:55

标签: vue.js

再次给我!

所以我有一个自己的组件:

<template>
<div class='mynewcomponent'>
  <v-layout>
    <v-flex xs12 sm6 offset-sm3>
      <v-card v-bind:style="{ backgroundColor: this.myColor}">
        <!-- Picture
        <v-img
          src="https://cdn.vuetifyjs.com/images/cards/sunshine.jpg"
          height="200px"
        >
        </v-img>
         -->
        <v-card-title primary-title>
          <div>
              <slot name="header">Top western road trips</slot>
              <br>
              <slot name="TestDesciption">1,000 miles of wonder</slot>
          </div>
        </v-card-title>

        <v-card-actions>
          <v-btn flat>Share</v-btn>
          <v-btn flat color="purple">Explore</v-btn>
          <v-spacer></v-spacer>
          <v-btn icon @click="show = !show">
            <v-icon>{{ show ? 'keyboard_arrow_down' : 'keyboard_arrow_up' }}</v-icon>
          </v-btn>
        </v-card-actions>

        <v-slide-y-transition>
          <v-card-text v-show="show">
            I'm a thing. But, like most politicians, he promised more than he could deliver. You won't have time for sleeping, soldier, not with all the bed making you'll be doing. Then we'll go with that data file! Hey, you add a one and two zeros to that or we walk! You're going to do his laundry? I've got to find a way to escape.
          </v-card-text>
        </v-slide-y-transition>
      </v-card>
    </v-flex>
  </v-layout>
  </div>
</template>


<script>
export default {
   data: () => ({
    show: false,
    myColor:'#ffffff'
  })
}
</script>

在我的about.vue中,我将其加载到for循环中:

<template>
<div class='about'>
  <mynewcomponent v-for="(item,index) in 100"/>>

    <template v-slot:header>
      <h3 style="text-align: left;"><span style="color: #3366ff">ID: 1234</span></h3>
    </template>
        <template v-slot:TestDesciption>
      <h3 style="text-align: left">example shit</h3>
    </template>
  </mynewcomponent>
</div>
</template>

<script>

import myNewComponent from '@/components/myNewComponent.vue'; // @ is an alias to /src
export default {
  name: 'about',
  components: {
    'mynewcomponent': myNewComponent
  }
}
</script>

现在我想要其他背景色的偶数和奇数卡。 我尝试了Google所说的一切,但没有成功。

如果索引%2 == 0 (偶数或奇数)

,我将通过颜色

如何在for循环中传递颜色?

或者有人可以告诉我一种更好的方法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以创建一个方法来绑定class属性,并将索引作为参数传递。对于每一行,您可以求值并向该元素返回不同的类。

您可以查看示例here

methods:{
		spanClass: function(index) {
			return {
				in: index % 2 === 0,
				out: index % 2 !== 0
			}
		}
li.in {
  background-color:red;
}

li.out {
  background-color:black;
}
<template>
<div class='about'>
  <mynewcomponent v-for="(item,index) in 100"/>>

    <template v-slot:header>
      <h3 style="text-align: left;"><span :class="spanClass(item)">ID: 1234</span></h3>
    </template>
        <template v-slot:TestDesciption>
      <h3 style="text-align: left">example shit</h3>
    </template>
  </mynewcomponent>
</div>
</template>