1. 程式人生 > >vue v-for 迴圈巢狀的探索(一)

vue v-for 迴圈巢狀的探索(一)

舉一個簡單的例子:

1、結構部分內容

(1)html 、css部分

<div class="Classfily" v-for="(subtitle) in pdata.subtitle">
<el-row>
<!--分類-->
 <el-col :span="24">
 <div class="grid-content bg-purple">
 <p class="red">{{subtitle.title}}</p>
 <!--{{subtitle.smalltitle}}-->
 <span v-for="smalltitle in subtitle.smalltitle">
 <span v-for="(one,index) in smalltitle.one" class="orange">
 {{one}}
 <!----{{index}}-->
 </span>
 ----
 <span v-for="(two,index) in smalltitle.two" class="gray">
 {{two}}
 <!----{{index}}-->
 </span>
 <br />
 </span>
</div>
 </el-col>
</el-row>

</div>

<style>
p{margin: 0;}
.orange{
color:orange;
}
.gray{
color: gray;
}
.red{
color: red;
}

</style>

(2)資料來源

<script>
export default {
  name: 'engine',
  data () {
    return {
    pdata:{
  "subtitle":[
   {
   "title":'辦公組',
   "smalltitle":[
      {
   "one":'組名1',
   "two":['組員1', '組員2','組員3',"組員4","組員5"]
      },
      {
      "one":'組名2',
      "two":['組員1', '組員2','組員3',"組員4","組員5"]
      }
   ]
   }
  ]
 
    }
    }
  }
}

</script>

2、迴圈巢狀的原理

(1)首先考慮最外層的資料是pdata,想要得到subtitle,必須從pdata中獲取,即最外層迴圈體

        v-for="(subtitle) in pdata.subtitle"             【括號內為要獲取的內容】

(2)其次要獲取subtitle下的title屬性,因title是在subtitle中包含的,故只有通過subtitle才能獲取

       <p class="red">{{subtitle.title}}</p>           【title無子屬性,不用有迴圈體,可直接通過已有的subtitle獲取】

(3)接下來要獲取subtitle下的smalltitle的值,獲取的是其下全部的值,為一個json物件

       <span v-for="smalltitle in subtitle.smalltitle">{{smalltitle}}</span>

(4)最後獲取subtitle的子屬性的值,要通過smalltitle來獲取對應的子屬性的值,則這部分迴圈體要巢狀在(3)

      <span v-for="(one,index) in smalltitle.one" class="orange">
    {{one}}
<!----{{index}}-->
     </span>
----
     <span v-for="(two,index) in smalltitle.two" class="gray">
{{two}}
     <!----{{index}}-->
     </span>

     <br />

注意:(1)因為subtitle的子屬性下還有各自的子屬性,故需要各自使用迴圈來遍歷出各自的值。

          (2)使用“------”和“<br />”標籤的位置,結合迴圈體考慮,此處不做詳解,可自行嘗試。

          (3)迴圈獲取誰,誰的名就在迴圈體對應的括號內。【  (one) in smalltitle.one  】

比較有意思的是各自的index的值,目前暫未理解,後續弄明白了再分享。