数据库设计:
后台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":"u7f51u7ad9u9996u9875","pId":"-1","isContent":false},
{"id":"2","name":"u5173u4e8eu6211u4eec","pId":"-1","isContent":true},
{"id":"3","name":"u516cu53f8u7b80u4ecb","pId":"2","isContent":true},
{"id":"4","name":"u516cu53f8u6587u5316","pId":"2","isContent":true},
{"id":"5","name":"u8363u8a89u8d44u8d28","pId":"2","isContent":true},
{"id":"6","name":"u5b9eu9a8cu5ba4u8ba4u8bc1","pId":"-1","isContent":true},
{"id":"7","name":"u5b9eu9a8cu5ba4u5e03u5c40u5efau7acb","pId":"6","isContent":true},
{"id":"8","name":"u4eeau5668u8bbeu5907u9009u62e9","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>