数据库设计:
后台PHP输出所有菜单数据(index.php):
<?php
header("Access-Control-Allow-Origin:*");header("Content-type:text/json;charset=utf-8");error_reporting(0);require_once ("database.php");$sql = "select * from v_menu";$re = excute_query($sql);$arr=[];while ($row = $re -> fetch_assoc()) { if($row["isContent"]=="0"){ $row["isContent"]=false; }else{ $row["isContent"]=true; } array_push($arr,$row);}echo json_encode($arr);?>输出结果:
[{"id":"1","name":"\u7f51\u7ad9\u9996\u9875","pId":"-1","isContent":false},
{"id":"2","name":"\u5173\u4e8e\u6211\u4eec","pId":"-1","isContent":true},
{"id":"3","name":"\u516c\u53f8\u7b80\u4ecb","pId":"2","isContent":true},
{"id":"4","name":"\u516c\u53f8\u6587\u5316","pId":"2","isContent":true},
{"id":"5","name":"\u8363\u8a89\u8d44\u8d28","pId":"2","isContent":true},
{"id":"6","name":"\u5b9e\u9a8c\u5ba4\u8ba4\u8bc1","pId":"-1","isContent":true},
{"id":"7","name":"\u5b9e\u9a8c\u5ba4\u5e03\u5c40\u5efa\u7acb","pId":"6","isContent":true},
{"id":"8","name":"\u4eea\u5668\u8bbe\u5907\u9009\u62e9","pId":"6","isContent":true},
......
]
vue文件(将数据转化为树级目录):
new Vue({
el: "#app", data() { return { data: [],//查看php文件夹下的menu.json文件 } }, created() { this.getAllList(); }, methods: { getAllList() { axios .get('http://localhost/PHP/vue.js/vue+.html+axios+php/sjlr/php/index.php') .then(response => { let data1 = response.data; // console.log(data); let tree = []; for (let i = 0; i < data1.length; i++) { //pId为-1的父节点 if (data1[i].pId == '-1') { let obj = data1[i] obj.list = [] tree.push(obj) data1.splice(i, 1) i-- } } if (data1.length != 0) { for (let i = 0; i < tree.length; i++) { for (let j = 0; j < data1.length; j++) { if (data1[j].pId == tree[i].id) { let obj = data1[j] obj.list = [] tree[i].list.push(obj) data1.splice(j, 1) j-- } } } } this.data = tree }) .catch(function(error) { // 请求失败处理 console.log(error); }); }, } })data数据:
........
生成菜单导航:
<el-menu theme="dark" class="el-menu-demo" mode="horizontal" background-color="#1d5daf" text-color="#fff" active-text-color="#0e81ce">
<template v-for="(item,index) in data"> <el-submenu :index=item.id v-if="item.isContent"> <template slot="title"> { {item.name}} </template> <template v-for="(menu,index) in item.list"> <el-menu-item :index=menu.id>{ {menu.name}}</el-menu-item> </template> </el-submenu> <el-menu-item :index=item.id v-else>{ {item.name}}</el-menu-item> </template> </el-menu>