v-for指令内部使用函数导致的奇怪现象

废话不多说,直接上代码。

<div class="father" v-for="(item,index) in testdiv" :key="index" style="display:inline-block;border:1px solid black;height:200px;width:200px;background: yellow;">
     <div style="display:inline-block;" v-if="index == 0"><span v-for="(oitem,oindex) in testSon" :key="oindex" >顶级==父级索引{{index}}>子级索引{{oindex}}------ 
         </span>
     </div>
     <div class=“son” style="display:inline-block;" v-if="index != 0"><span v-for="(oitem,oindex) in testmethod(index)" :key="oindex" >父级索引{{index}}>子级索引{{oindex}}-- 
     --------</span>
     </div>
</div>

data() {
    return {
        testdiv:[0, 1],
        testSon:['子1', '子2', '子3', '子4']
}

methods: {
//每次给顶级div的v-for循环的数组新增1条元素,直到该数组长度为4
  testmethod(index) {
      //此处会出现问题,因为传递过来的index值会是错乱的,所以加入了下方的return
      if(index != this.testdiv[this.testdiv.length-1]){
        return;
      }
      if(this.testdiv.length<4) {
        this.testdiv.push(index+1)
      }
      return this.testSon
    },
}

最终效果

img


中间testmethod方法并不是和我想象的一样只会调用三次,因为除了第一个.father,后面只循环了三个.father,但是实际上testmethod方法会被调用出乎意料多的次数,并且与.son的v-for是无关的,请问是为什么

v-for和if不建议一起使用。 当 v-if 与 v-for 一起使用时,v-for 具有比 v-if 更高的优先级