vue的遞歸組件以及三級菜單的制作


js里面有遞歸算法,同時,我們也可以利用props來實現vue模板的遞歸調用,但是前提是組件擁有 name 屬性

父組件:slotDemo.vue:

<template>
  <div>
    <!-----遞歸組件----->
    <ul>
      <simple3 :tree="item" v-for="item in tree"></simple3>
    </ul>

  </div>
</template>
<style lang="stylus" rel="stylesheet/stylus">
  li
   padding-left 30px
</style>
<script>
  import simple3 from "./simple/simple3.vue";
  export default{
    data(){
      return {
        tree: [{
          label: "一級菜單",
          test:1,
          children: [{
            label: "二級菜單",
            test:2,
            children: [{
              label: "三級菜單",
              test:3
            }]
          }]
        }]
      }
    },

    components: {
     
      simple3
    }
  }
</script>

  子組件:simple3.vue

<template>
  <li>
    <a>{{tree.label}}</a>
    <simple3 v-if="tree.children" :tree="item" v-for="item in tree.children" :class="item.test==2?'test2':'test3'"></simple3>

  </li>
</template>
<style rel="stylesheet/stylus" lang="stylus">
    .test2
      list-style disc

    .test3
      list-style decimal
</style>
<script>
  export default{
    name: "simple3",
    props: ["tree"]
  }
</script>

  

上面是一個子組件,定義了 name 為 simple03,然后在模板中調用自身,結合 v-for 實現遞歸

為了防止出現死循環,在調用自身的時候,加入了 v-if 作為判定條件

父組件中調用的時候,需要通過 props 傳入一個 tree;

為了對每一級菜單有所區分,我對tree里面的每一個子集合里面加了一個test字段來區分是哪一級的菜單然后對其不同的樣式進行處理

最后的效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM