我可以使用嵌套在“方法”中的“ v-for”中的“ index”参数吗?

时间:2019-12-24 19:57:29

标签: javascript vue.js v-for

我需要在v-for上使用索引,但必须在与directive本身相同的级别上使用索引,以便mutate所显示的状态。

<template>
  <div>
    <div v-for="share in sharesPurchased()" :key="share">
      <div>
        <h4>This is some content</h4>
        <p style="border: solid 1px">{{share.count}}</p>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    data(){
      return {
        shares: [
          {id: 'BMW', count: 1},
          {id: 'Ford', count: 0},
          {id:'Apple', count: 10}
        ]
      }
    },
    methods: {
      sharesPurchased() {
// I want to use this at the v-for level to limit content view
      }
    }
  }
</script>

我想限制这次迭代中显示的内容,因此我只显示count > 0的内容,即:shares[i].count > 0

如上所述,我意图的结果应该是<p style="border: solid 1px">{{share.count}}</p>仅显示1,因为只有this.shares[0].count>,然后是0

1 个答案:

答案 0 :(得分:3)

更新:根据您的使用需要,这显然是X-Y问题。您应该改用计算属性:

computed: {
    filteredSharesByCount: function() {
        return this.shares.filter(share => share.count > 0);
    }
}

然后您可以在模板中引用它:


过时的答案:

v-for绑定中的index is accessible as the second optional argument

  

v-for还支持当前项目索引的第二个可选参数。

即:

<div v-for="(share, idx) in sharesPurchased(shares)" :key="share">

然后,如果您希望某个方法可以访问索引,则可以在循环内简单地使用idx