VueJS使用数组元素上的条件循环数组(v-for with v-if)

时间:2017-02-18 09:50:29

标签: javascript vuejs2 vue.js v-for

我正在尝试做的是在 v-for 循环中打印两列牌元素。因此,如果索引是pair,我将连续打印数组的当前元素,并跳过奇数索引的元素。

到目前为止我的代码:

  <template>
    <q-layout>
    <!-- Main block start-->
    <div v-if="!showBack" class="card scroll" id="cards-view">
      <div class="layout-padding">
        <p class="group">
          <button class="primary circular fixed-bottom add-btn"><router-link to="/create" exact><i class="icon-32 text-white">add</i></router-link></button>
        </p>
        <div class="row content-center text-center gutter" v-for="(index, pet) in pets" v-if="index % 2 === 0">
          <div class="auto ">
            <div class="shadow-1">
              <img class="responsive" :src="pets[index].name">
              <div class="card-content text-bold">
                <img class="responsive sex" :src="pets[index].sex">{{ pets[index].name }}
              </div>
            </div>
          </div>
          <div class="auto ">
            <div class="shadow-1">
              <img class="responsive" :src="pets[index+1].name">
              <div class="card-content text-bold">
                <img class="responsive sex" :src="pets[index+1].sex">{{ pets[index+1].name }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Man block end-->

    <!--- Content -->
    <router-view class="layout-view"></router-view>

  </q-layout>
</template>

<script>

export default {
  data () {
    return {
      pets: [{
          name: 'Júpiter',
          sex: 'statics/img/female.jpg',
          photo: 'statics/img/jupiter.jpg'
        },{
          name: 'Ringo',
          sex: 'statics/img/male.jpg',
          photo: 'statics/img/ringo.jpg'
        }
      ]
    }
  }
}
</script>

但我收到了下一个错误:

  

[Vue警告]:在...处呈现匿名组件时出错

     

vue.runtime.common.js?d43f:435 TypeError:无法读取属性“photo”   未定义的       在eval(eval at 167(0.cd4853d ... .js:28),:95:31)......

基本上,我正在尝试对我正在循环的数组元素进行循环。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:2)

只需改变:

v-for="(pet, index) in pets"

要:

  <html>
  <head>
    <title>

    </title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div id="container">
      <div id="header">
        My header
      </div>
      <div id="content">
        <div id="nav"></div>
      </div>
      <div id="footer"></div>
    </div>
  </body>
</html>