0

I am working with VueJS. Given a markup which looks like this:

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

I would like to display the number of times the condition is met. So, if the condition is met 3 times, I would like to see the <p> markup like so:

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

where 1,2,3 are the times the condition is met.

How do I go about achieving this?

laptou
  • 6,389
  • 2
  • 28
  • 59
JohnJ
  • 6,736
  • 13
  • 49
  • 82
  • 1
    Possible solution using CSS only https://stackoverflow.com/questions/37830238/is-there-any-way-to-insert-an-elements-index-child-number-as-text-within-the – Eric Guan Dec 30 '19 at 01:28

2 Answers2

0

You can implement this by watching a property:

On your Vue instance:

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++
      }
    }
  }
})

Then if you want to display a <p> for each occurrence, you can do it with a v-for:

<p v-for="index in occurrences" :key="index">
  This is the {{ index }}th time the condition has become true.
</p>
laptou
  • 6,389
  • 2
  • 28
  • 59
0

I guess you should to filter your data:

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>
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15