【问题标题】:vuejs display number of times a v-if condition is metvuejs显示满足v-if条件的次数
【发布时间】:2019-12-30 01:11:13
【问题描述】:

我正在使用 VueJS。给定一个如下所示的标记:

<template v-for="item in some_counter">
  <p v-if="item.some_param1 !== 'None'">
   [[ item.some_param2 ]]
  </p>
</template>

我想显示满足条件的次数。因此,如果条件满足 3 次,我希望看到 &lt;p&gt; 标记如下:

<p>1, some_value1</p>
<p>2, some_value2</p>
<p>3, some_value3</p>

其中1,2,3 是满足条件的次数。

我该如何实现这一目标?

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

你可以通过观察一个属性来实现:

在您的 Vue 实例上:

export default Vue.extend({
  data { occurrences: 0 },
  computed: { myProp: function() { return this.item.some_param1 !== 'None' } },
  watch: {
    myProp: function (val, oldVal) {
      if (val && !oldVal) {
        // myProp has changed from true to false
        this.occurrences++
      }
    }
  }
})

然后,如果您想在每次出现时显示&lt;p&gt;,您可以使用v-for

<p v-for="index in occurrences" :key="index">
  This is the {{ index }}th time the condition has become true.
</p>

【讨论】:

    【解决方案2】:

    我猜你应该过滤你的数据:

    new Vue({
      el: '#app',
      data: {
        items: [
          { some_param1: 'foo1', some_param2: 'bar1' },
          { some_param1: 'None', some_param2: 'bar2' },
          { some_param1: 'foo3', some_param2: 'bar3' },
        ],
        filteredItems: []
      },
      mounted () {
        this.filteredItems = this.items.filter(item => item.some_param1 !== 'None')
      }
    })
    p {
     margin: 0;
    }
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    
    <div id="app">
      <p v-for="(item, index) in filteredItems" :key="index">
       {{ index + 1 }}, {{ item.some_param2 }}
      </p>
    </div>

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 2020-10-04
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多