Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed vs method inside nested v-for loop according to Vue docs

On this page, it says that:

In situations where computed properties are not feasible (e.g. inside nested v-for loops), you can use a method

However, I am able to use computed props inside a nested v-for loop (check fiddle)

new Vue({
  el: '#sample',
  data() {
    return {
      numbers: [1, 2, 3, 4, 5]
    }
  },
  computed: {
    even() {
      return this.numbers.filter(n => n % 2 === 0)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="sample">
  <div v-for="n in numbers">
    {{n}}
    <div v-for="e in even">
      ..{{e}}
    </div>
  </div>
</div>

What am I missing?

like image 945
Abhishek Jain Avatar asked Apr 20 '26 02:04

Abhishek Jain


1 Answers

Okay so I believe the docs mean that computed properties are not feasible inside nested v-for loops, if, for instance, the inner array depends on the current outer array element.

As a quick example, imagine we want a loop which displays numbers from 1 through 5. And after each number N, we need a nested loop which will contain all the whole numbers leading up to the number N.

Check fiddle to see what I'm talking about.

new Vue({
  el: '#sample',
  data() {
    return {
      numbers: [1, 2, 3, 4, 5]
    }
  },
  methods: {
    getLeadingNbs(n) {
    	return (Array(n)+'').split(',').map( (n,i) => i )
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="sample">
  <div v-for="n in numbers">
    {{n}}
    <div v-for="l in getLeadingNbs(n)">
      ....{{l}}
    </div>
    <br>
  </div>
</div>
like image 160
Abhishek Jain Avatar answered Apr 22 '26 14:04

Abhishek Jain