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>

    

 

 

 

 

 

 

 

 

 


免責聲明!

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



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