vue左侧菜单的实现

后端实现

django视图
def menu(request): menu_list = models.Menu.objects.all().values('id', 'menu_name', 'parent_id') l = [] dic = {} for item in menu_list: if int(item['parent_id']) == 0: l.append({ 'id': item['id'], 'name': item['menu_name'], 'children' : [] }) else: for i in l: if int(item['parent_id']) == int(i['id']): i['children'].append(item) dic['data'] = l return JsonResponse(dic)

得到的数据格式

 {
    'data':
        [
            {
                'id': 1,
                'name': '一级菜单(1)',
                'children': [
                     {'id': 2, 'menu_name': '一级菜单的儿子1', 'parent_id': '1'},
                     {'id': 3, 'menu_name': '一级菜单的儿子2', 'parent_id': '1'}
                ]},
            {
                'id': 4,
                'name': '一级菜单(2)',
                'children': [
                    {'id': 5, 'menu_name': '一级菜单的儿子1', 'parent_id': '4'},
                    {'id': 6, 'menu_name': '一级菜单的儿子2', 'parent_id': '4'}]
            }
        ]
}

vue实现

            <el-menu
                      background-color="RGB(52,58,64)"
                      text-color="#fff"
                      active-text-color="#ffd04b">
                      <!-- 一级菜单 -->
                    // 点击的时候要有效果 : 来绑定
                                   v-for 循环要有:key <el-submenu :index="item.id + '' " v-for="item in menuList" :key="item.id"> <!-- 一级菜单模板区 --> <template slot="title"> <!-- 图标和文本 --> <i class="el-icon-location"></i> <span>{{item.name}}</span> </template> <!-- 二级菜单 --> <el-menu-item :index="sonChildren.id + ''" v-for="sonChildren in item.children" :key="sonChildren.id"> <template slot="title"> <!-- 图标和文本 --> <i class="el-icon-location"></i> <span>{{sonChildren.menu_name}}</span> </template> </el-menu-item> </el-submenu> </el-menu>
<script>
      export default {
          data(){
              return{
                  menuList:[]
              }
              
          },
    // 一启动就加载 created(){
this.getMenuList() }, methods: { getMenuList(){
        // 发送请求
this.$axios.get('http://127.0.0.1:8000/menu/',{}) .then((response)=> { console.log(response.data);
            // 赋值到data()里
this.menuList = response.data.data }).catch((error) =>{ }) } }, } </script>

    

原文地址:https://www.cnblogs.com/a438842265/p/12196433.html