Home > Back-end >  How to increment property in loop Vue 2?
How to increment property in loop Vue 2?

Time:08-06

Template : have function in curly braces setSr() for increment previous property

<ul v-for="i in 5" :key="i">
    <li>{{setSr()}} {{i}} {{ preivous  }} </li>
  </ul>

data property previous initial 1

 data(){
        return{
               preivous:1,
              }
       }

Method

methods:{
        setSr(){
                 this.preivous =(this.preivous 1); 
            }
     }

Output

1 2022 2 2023 3 2024 4 2025 5 2026

Expected output next want increment previous by condition wise

1 0 2 1 3 2 4 3 5 4

CodePudding user response:

If you just will use preivous for render do the following and will get the output you want it:

var app = new Vue({
  el: '#app',
  data: {
   
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
 <ul v-for="i in 5" :key="i">
    <li>{{i}} {{ 2021 i  }} </li>
  </ul>
</div>

CodePudding user response:

Avoid on-the-fly stuff like this in the template loop and do stuff like this and restructure what's needed before you output.

For example, make a range method to compute your range, if your use it ever again, abstract it into a mixin etc, and then use a computed value to call it, setting a default in data.

const utilsMixin = {
  methods: {
    range(start, end, step) {
      // ascii a-z
      if (typeof start === 'string' && typeof end === 'string') {
        const result = []
        for (let idx = start.charCodeAt(0), e = end.charCodeAt(0); idx <= e;   idx) {
          result.push(String.fromCharCode(idx))
        }
        return result
      }
      // number or date
      const range = []
      typeof step === 'undefined' && (step = 1)
      if (end < start) {
        step = -step
      }
      while (step > 0 ? end >= start : end <= start) {
        range.push(start)
        start  = step
      }
      return range
    }
  }
}

var app = new Vue({
  el: '#app',
  mixins: [
    utilsMixin
  ],
  data: () => ({
    limit: 5
  }),
  computed: {
    years() {
      return this.range(new Date().getFullYear(), new Date().getFullYear()   this.limit)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
  <ul>
    <li v-for="(year, i) in years" :key="i">{{i}} {{ year }} </li>
  </ul>
</div>

  • Related