vue 递归菜单树

做一个后台管理系统, 很多时候是不会只有一两层这种定死的数据结构的, 往往,我们不知道它会有多少层数据, 这就需要我们来递归渲染, 而再react中我们递归个菜单就比较方便, 跟平时写递归函数差不多, 而在vue中,我们就需要递归组件了,那vue中问么递归组件呢, 其实就是依靠 组件中的name属性,这个name的值,就是当前组件自身, 举个例子,

<template>
  <div>
    <hello />
  </div>
</template>

<script>
export default {
  name: 'hello'
}
</script>

<style lang="scss" scoped>
</style>

明白了这一点,就知道怎么玩递归菜单了,

至于不会写递归函数的小伙伴, 就需要你自己去学学了,不然很容易写出死循环, 然后控制台报个调用栈溢出的错误

以下以elementui 的菜单举例子,  直接上模拟数据了, 就不解释了

App.vue

<template>
  <el-col :span="4">
    <el-menu default-active="2">
      <SecondMenu v-for="item in list" :key="item.id" :item="item" />
    </el-menu>
  </el-col>
</template>

<script>
import SecondMenu from './SecondMenu'
export default {
  data() {
    return {
      list: [
        {
          id: '1',
          title: '导航一',
          children: [
            {
              id: '1-1',
              title: '选项1',
              children: [
                {
                  id: '1-1-1',
                  title: '选项1-1-1'
                }
              ]
            },
            {
              id: '1-2',
              title: '选项2'
            }
          ]
        },
        {
          id: '2',
          title: '导航二',
          children: [
            {
              id: '2-1',
              title: '选项2-1'
            },
            {
              id: '2-2',
              title: '选项2-2'
            }
          ]
        },
        {
          id: '3',
          title: '导航三'
        }
      ]
    }
  },
  components: {
    SecondMenu
  }
}
</script>

SecondMenu.vue

<template>
  <div>
    <el-submenu :key="item.id" :index="item.id" v-if="item.children">
      <template slot="title">
        <i class="el-icon-location"></i>
        <span>{{ item.title }}</span>
      </template>
      <SecondMenu
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        class="nest-menu"
      />
    </el-submenu>
    <el-menu-item :index="item.id" v-else>
      <i class="el-icon-setting"></i>
      <span slot="title">{{ item.title }}</span>
    </el-menu-item>
  </div>
</template>

<script>
export default {
  name: 'SecondMenu',
  components: {},
  props: {
    item: {
      type: Object,
      default: () => {}
    }
  }
}
</script>

<style lang="scss" scoped></style>

下边就是路由菜单了, (这里只说路由前端定好的, 而不是从后台拿的路由, 即使是权限配置的, 都差不多)

发布了63 篇原创文章 · 获赞 100 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/qq_36407748/article/details/103427399