1. 程式人生 > 實用技巧 >vue 遞迴 無限極

vue 遞迴 無限極

    demo(父元件向子元件傳值,將子元件註冊進父元件中,父元件擁有子元件的功能)

  • index.js
    • import Parent from '@/components/Parent'
      
      
      
      Vue.use(Router)
      
      export default new Router({
        mode: 'history',
        routes: [
          {
            path: '/',
            name: 'HelloWorld',
            component: HelloWorld
          },
          {
            path: '/Parent',
            name: 'Parent',
            component: Parent
          },
        ]
      })

  • list.vue
    • <template>
          <div>
              <div class="list-item" v-for="(item, index) in list" :key="index">
                  <div class="item-name">
                      <span>{{item.name}}</span>
                  </div>
                  <div v-if="item.children" class="children-item">
                      <list :list="item.children"></list>
                  </div>
              </div>
          </div>
      </template>
      <script>
      export 
      default { //利用名稱空間呼叫,遞迴裡必須用name name: "List", //通過props屬性來宣告一個自己的屬性,然後父元件就可以往裡面傳遞資料 props: { list: Array } }; </script> <style> .list-item{ padding-left: 20px; list-style: none; } </style>

  • Parent.vue
    • <template>
          <div class="list-detail">
            <list :list="list"></list>
          </div>
      </template>
      <script>
      //
      匯入子元件 import List from './list' export default { name: "Parent", //註冊子元件,應用 components: { List }, data() { return { list: [{ name: "少年", children: [{ name: "欣總", children: [{ name: "666" }, { name: "666" }] },{ name: "管總", children: [{ name: "777" }, { name: "777" }] }] }] } } } </script>

  • 效果
    •