1.我们先启动商品微服务和renren-fast微服务,然后启动前端项目renren-fast-vue项目(以admin admin 进行登录)
新建一个一级目录
在创建一个菜单
2.编写Categorycontrolelr
/**
* 查出所有分类以及子类,以树形结构组装起来
*/
@RequestMapping("/list/tree")
//@RequiresPermissions("product:category:list")
public R list(@RequestParam Map<String, Object> params){
List<CategoryEntity> entities = categoryService.listWithTree();
return R.ok().put("data","");
}
3.编写Categoryservice
List<CategoryEntity> listWithTree();
4.编写CategoryServiceImpl
@Override
public List<CategoryEntity> listWithTree() {
//1.查询所有的分类以及子类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2.将分类和子类组装成树形
//2.1先获取一级分类
List<CategoryEntity> levelMenus = entities.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == 0;
}).map(menu ->{
menu.setChildren(getChildren(menu,entities));
return menu;
}).sorted((menu1,menu2)->{
return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
}).collect(Collectors.toList());
return levelMenus;
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity -> {
//1.找到子菜单
categoryEntity.setChildren(getChildren(categoryEntity, all));
return categoryEntity;
}).sorted((menu1, menu2) -> {
//2.菜单的排序
return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
}).collect(Collectors.toList());
return children;
}
5.测试成功
6,来到前端项目创建category.vue文件
参考Element ui 树形控件
<template>
<el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
</template>
<script>
export default {
data() {
return {
menus: [],
defaultProps: {
children: 'children',
label: 'name'
}
};
},
created(){
this.getMenus();
},
computed:{
},
methods:{
handleNodeClick(data) {
console.log(data);
},
getMenus(){
this.dataListLoading = true
this.$http({
url: this.$http.adornUrl('/product/category/list/tree'),
method: 'get',
}).then(({data}) => {
console.log("成功获取到菜单数据。。。。",data.data)
this.menus =data.data;
})
},
// 新增 / 修改
addOrUpdateHandle (id) {
this.addOrUpdateVisible = true
this.$nextTick(() => {
this.$refs.addOrUpdate.init(id)
})
}
},
}
</script>
<style lang="scss" scoped>
</style>
修改路径文件(让前端所有发出的请求经过GateWay网关)
配置其GateWay网关 在application.yml中配置
uri: lb://renren-fast lb是负载均衡 路由到renren-fast微服务上
predicates:
- Path=/api/** 断言其api下的所有路径
fileters过滤器
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment} 就是替换路径将/api/ 替换为/renren-fast/
- id: product-route
uri: lb://gulimall-product
predicates:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<segment>.*),/$\{segment}
- id: admin_route
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
这时候我们请求可能会遇到跨域问题(因为我们访问的路径和请求的路径不同出现跨域)
我们需要在GateWay中进行配置
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1.配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
然后我们再去访问测试成功
实现三级分类的增删改
1.实现增删改功能(前端代码)
<template>
<div>
<el-tree
:data="menus"
:props="defaultProps"
:expand-on-click-node="false"
show-checkbox
node-key="catId"
:default-expanded-keys="expandedKey"
draggable
:allow-drop="allowDrop"
>
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button
v-if="data.catLevel <= 2"
type="text"
size="mini"
@click="() => append(data)"
>
Append
</el-button>
<el-button
v-if="node.childNodes.length == 0"
type="text"
size="mini"
@click="() => remove(node, data)"
>
Delete
</el-button>
<el-button type="text" size="mini" @click="() => edit(data)">
Edit
</el-button>
</span>
</span>
</el-tree>
<el-dialog
:title="title"
:visible.sync="dialogVisible"
width="30%"
:close-on-click-modal="false"
>
<el-form :model="category">
<el-form-item label="分类名称">
<el-input v-model="category.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="图标">
<el-input v-model="category.icon" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="计量单位">
<el-input
v-model="category.productUnit"
autocomplete="off"
></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitData">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import Vue from "vue";
import http from "../../../utils/httpRequest";
export default {
data() {
return {
maxLevel: 0,
title: "",
dialogType: "", //edit add
category: {
name: "",
parentCid: 0,
catLevel: 0,
showStatus: 1,
sort: 0,
catId: null,
productUnit: "",
icon: "",
},
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: "children",
label: "name",
},
};
},
created() {
this.getMenus();
},
computed: {},
methods: {
getMenus() {
this.dataListLoading = true;
this.$http({
url: this.$http.adornUrl("/product/category/list/tree"),
method: "get",
}).then(({ data }) => {
console.log("成功获取到菜单数据。。。。", data.data);
this.menus = data.data;
});
},
allowDrop(draggingNode, dropNode, type) {
//1.被拖动的当前节点以及所在的父节点总层数不能大于3
//1.1 被拖动的当前节点层数
console.log("allowdrop", draggingNode, dropNode, type);
//
this.countModelevel(draggingNode.data);
//当前正在拖动的节点-父节点所在的深度不大于3即可
let deep = this.maxLevel - draggingNode.data.catLevel + 1;
console.log("最大深度", deep);
if (type == "inner") {
return (deep + dropNode.level) <= 3;
} else {
return (deep + dropNode.parent.level) <= 3;
}
},
countModelevel(node) {
//找到所有子节点,求出最大深度
if (node.children != null && node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
if (node.children[i].catLevel > this.maxLevel) {
this.maxLevel = node.children[i].catLevel;
}
this.countModelevel(node.children[i]);
}
}
},
edit(data) {
this.title = "修改分类";
this.dialogType = "edit";
console.log("要修改的数据", data);
this.dialogVisible = true;
//发送请求获取当前节点最新数据
this.$http({
url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
method: "get",
}).then(({ data }) => {
//请求成功
console.log("要回显的数据", data);
this.category.name = data.data.name;
this.category.catId = data.data.catId;
this.category.icon = data.data.icon;
this.category.productUnit = data.data.productUnit;
this.category.parentCid = data.data.parentCid;
this.category.catLevel = data.data.catLevel;
this.category.sort = data.data.sort;
this.category.showStatus = data.data.showStatus;
});
},
append(data) {
this.title = "添加分类";
this.dialogType = "add";
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
this.category.catId = null;
this.category.name = null;
this.category.icon = "";
this.category.productUnit = "";
this.category.sort = 0;
this.category.showStatus = 1;
},
submitData() {
if (this.dialogType == "add") {
this.addCategory();
}
if (this.dialogType == "edit") {
this.editCategory();
}
},
//修改三级分类
editCategory() {
var { catId, name, icon, productUnit } = this.category;
var data = {
catId: catId,
name: name,
icon: icon,
productUnit: productUnit,
};
this.$http({
url: this.$http.adornUrl("/product/category/update"),
method: "post",
data: this.$http.adornData(data, false),
}).then(({ data }) => {
this.$message({
message: "菜单修改成功",
type: "success",
});
//关闭对话框
this.dialogVisible = false;
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [this.category.parentCid];
});
},
//添加三级分类
addCategory() {
console.log("提交的三级分类数据", this.category);
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false),
}).then(({ data }) => {
this.$message({
message: "保存成功",
type: "success",
});
//关闭对话框
this.dialogVisible = false;
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [this.category.parentCid];
});
},
remove(node, data) {
var ids = [data.catId];
this.$confirm(`是否删除【${data.name}】菜单`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
this.$http({
url: this.$http.adornUrl("/product/category/delete"),
method: "post",
data: this.$http.adornData(ids, false),
}).then(({ data }) => {
this.$message({
message: "删除成功",
type: "success",
});
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [node.parent.data.catId];
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
});
});
},
};
</script>
<style lang="scss" scoped>
</style>
2.后端代码
CategoryController
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("product:category:save")
public R save(@RequestBody CategoryEntity category){
categoryService.save(category);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("product:category:update")
public R update(@RequestBody CategoryEntity category){
categoryService.updateById(category);
return R.ok();
}
/**
* 删除
* @RequestBody :获取请求体 必须发送POST请求
* SpringMVC 自动将请求体数据(JSON)转化为对应的对象
*/
@RequestMapping("/delete")
//@RequiresPermissions("product:category:delete")
public R delete(@RequestBody Long[] catIds){
//categoryService.removeByIds(Arrays.asList(catIds));
//1.检查当前删除的菜单,是否被别的地方引用
categoryService.removeMenuByIds(catIds);
return R.ok();
}
service层代码
PageUtils queryPage(Map<String, Object> params);
List<CategoryEntity> listWithTree();
void removeMenuByIds(Long[] catIds);
/**
* 逻辑删除菜单
*/
@Override
public void removeMenuByIds(Long[] catIds) {
//TODO 1.检查当前删除的菜单,是否被别的地方引用
baseMapper.deleteBatchIds(Arrays.asList(catIds));
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map(categoryEntity -> {
//1.找到子菜单
categoryEntity.setChildren(getChildren(categoryEntity, all));
return categoryEntity;
}).sorted((menu1, menu2) -> {
//2.菜单的排序
return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
}).collect(Collectors.toList());
return children;
}
注意:逻辑删除
1.配置全局的逻辑删除规则(可省略)
2.配置逻辑删除的组件Bean (3.1.0以上可省略)
3.给逻辑删除的字段添加注解@TableLogic
三级分类实现拖拽功能 以及 批量删除功能
<template>
<div>
<el-switch
v-model="draggable"
active-text="开启拖拽"
inactive-text="关闭拖拽"
></el-switch>
<el-button v-if="draggable" @click="batchSave">批量保存</el-button>
<el-button @click="batchDelete" type="danger">危险按钮</el-button>
<el-tree
:data="menus"
:props="defaultProps"
:expand-on-click-node="false"
show-checkbox
node-key="catId"
:default-expanded-keys="expandedKey"
:draggable="draggable"
:allow-drop="allowDrop"
@node-drop="handleDrop"
ref="menuTree"
>
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button
v-if="data.catLevel <= 2"
type="text"
size="mini"
@click="() => append(data)"
>
Append
</el-button>
<el-button
v-if="node.childNodes.length == 0"
type="text"
size="mini"
@click="() => remove(node, data)"
>
Delete
</el-button>
<el-button type="text" size="mini" @click="() => edit(data)">
Edit
</el-button>
</span>
</span>
</el-tree>
<el-dialog
:title="title"
:visible.sync="dialogVisible"
width="30%"
:close-on-click-modal="false"
>
<el-form :model="category">
<el-form-item label="分类名称">
<el-input v-model="category.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="图标">
<el-input v-model="category.icon" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="计量单位">
<el-input
v-model="category.productUnit"
autocomplete="off"
></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitData">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import Vue from "vue";
import http from "../../../utils/httpRequest";
export default {
data() {
return {
pCId:[],
draggable: false,
updateNodes: [],
maxLevel: 0,
title: "",
dialogType: "", //edit add
category: {
name: "",
parentCid: 0,
catLevel: 0,
showStatus: 1,
sort: 0,
catId: null,
productUnit: "",
icon: "",
},
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: "children",
label: "name",
},
};
},
created() {
this.getMenus();
},
computed: {},
methods: {
getMenus() {
this.dataListLoading = true;
this.$http({
url: this.$http.adornUrl("/product/category/list/tree"),
method: "get",
}).then(({ data }) => {
console.log("成功获取到菜单数据。。。。", data.data);
this.menus = data.data;
});
},
batchDelete(){
let checkedNodes = this.$refs.menuTree.getCheckedNodes();
console.log("被选中的",checkedNodes);
let catIds = [];
for(let i =0;i<checkedNodes.length;i++){
catIds.push(checkedNodes[i].catId);
}
this.$confirm(`是否批量删除【${catIds}】菜单`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
}).then(()=>{
this.$http({
url: this.$http.adornUrl("/product/category/delete"),
method: "post",
data: this.$http.adornData(catIds, false),
}).then(({ data }) => {
this.$message({
message: "批量删除成功",
type: "success",
});
this.getMenus();
}).catch(()=>{
this.$message({
type: "info",
message: "已取消删除",
});
});
});
},
batchSave() {
this.$http({
url: this.$http.adornUrl("/product/category/update/sort"),
method: "post",
data: this.$http.adornData(this.updateNodes, false),
}).then(({ data }) => {
this.$message({
message: "菜单顺序移动成功",
type: "success",
});
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = this.pCId;
this.updateNodes = [];
this.maxLevel = 0;
this.pCId = [];
});
},
handleDrop(draggingNode, dropNode, dropType, ev) {
console.log("tree drop: ", draggingNode, dropNode, dropType);
//1.当前节点最新的父节点Id
let pCId = 0;
let siblings = null;
if (dropType == "before" || dropType == "after") {
pCId =
dropNode.parent.data.catId == undefined
? 0
: dropNode.parent.data.catId;
siblings = dropNode.parent.childNodes;
} else {
pCId = dropNode.data.catId;
siblings = dropNode.childNodes;
}
//2.当前拖拽节点的最新顺序
for (let i = 0; i < siblings.length; i++) {
//判断当前节点是否是拖拽的节点
if (siblings[i].data.catId == draggingNode.data.catId) {
let catLevel = draggingNode.level;
if (siblings[i].level != draggingNode.level) {
//当前节点的层级发生变化
catLevel = siblings[i].level;
//递归修改字节点的层级
this.updateChildNodeLevel(siblings[i]);
}
this.updateNodes.push({
catId: siblings[i].data.catId,
sort: i,
parentCid: pCId,
catLevel: catLevel,
});
} else {
this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
}
this.pCId.push(pCId);
}
//3.当前拖拽节点的最新层级
console.log("updateNodes", this.updateNodes);
},
updateChildNodeLevel(node) {
if (node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
var cNode = node.childNodes[i].data;
this.updateNodes.push({
catId: cNode.catId,
catLevel: node.childNodes[i].level,
});
this.updateChildNodeLevel(node.childNodes[i]);
}
}
},
allowDrop(draggingNode, dropNode, type) {
//1.被拖动的当前节点以及所在的父节点总层数不能大于3
// 1) 被拖动的当前节点的深度
console.log("allowDrop: ", draggingNode, dropNode, type);
//递归计算 当前正在拖动的节点深度, 存储到maxLevel 中
this.countNodeLevel(draggingNode);
// 2) 当前正在拖动的节点深度+ 父节点所在的深度 不大于3
console.log("当前正在拖动节点的深度: ", this.maxLevel);
// 实际的深度
let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
console.log("深度:", deep);
if (type == "inner") {
//打印拖到内部时的 深度
console.log(
`this.maxLevel:${this.maxLevel};draggingNode.data.catLevel:${draggingNode.data.catLevel};dropNode.level:${dropNode.level}`
);
// 把某个菜单, 拖进某个菜单里面的时候, 需要进行当前节点的深度和被拖进去的节点的深度相加是否大于3
return deep + dropNode.level <= 3;
} else {
//拖到前面或者后面的时候的情况
//深度 加上父节点的深度, 小于等于3 ,就能拖动
return deep + dropNode.parent.level <= 3;
}
},
// 统计节点深度
countNodeLevel(node) {
//找到所有子节点,求出最大深度
if (node.childNodes != null && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
// 遍历循环所有的子节点
if (node.childNodes[i].level > this.maxLevel) {
// 如果某个树的子节点, 大于最大的节点, 那么就存储最大的深度
this.maxLevel = node.childNodes[i].level;
}
//递归调用 查找最大深度
this.countNodeLevel(node.childNodes[i]);
}
}
},
edit(data) {
this.title = "修改分类";
this.dialogType = "edit";
console.log("要修改的数据", data);
this.dialogVisible = true;
//发送请求获取当前节点最新数据
this.$http({
url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
method: "get",
}).then(({ data }) => {
//请求成功
console.log("要回显的数据", data);
this.category.name = data.data.name;
this.category.catId = data.data.catId;
this.category.icon = data.data.icon;
this.category.productUnit = data.data.productUnit;
this.category.parentCid = data.data.parentCid;
this.category.catLevel = data.data.catLevel;
this.category.sort = data.data.sort;
this.category.showStatus = data.data.showStatus;
});
},
append(data) {
this.title = "添加分类";
this.dialogType = "add";
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
this.category.catId = null;
this.category.name = null;
this.category.icon = "";
this.category.productUnit = "";
this.category.sort = 0;
this.category.showStatus = 1;
},
submitData() {
if (this.dialogType == "add") {
this.addCategory();
}
if (this.dialogType == "edit") {
this.editCategory();
}
},
//修改三级分类
editCategory() {
var { catId, name, icon, productUnit } = this.category;
var data = {
catId: catId,
name: name,
icon: icon,
productUnit: productUnit,
};
this.$http({
url: this.$http.adornUrl("/product/category/update"),
method: "post",
data: this.$http.adornData(data, false),
}).then(({ data }) => {
this.$message({
message: "菜单修改成功",
type: "success",
});
//关闭对话框
this.dialogVisible = false;
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [this.category.parentCid];
});
},
//添加三级分类
addCategory() {
console.log("提交的三级分类数据", this.category);
this.$http({
url: this.$http.adornUrl("/product/category/save"),
method: "post",
data: this.$http.adornData(this.category, false),
}).then(({ data }) => {
this.$message({
message: "保存成功",
type: "success",
});
//关闭对话框
this.dialogVisible = false;
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [this.category.parentCid];
});
},
remove(node, data) {
var ids = [data.catId];
this.$confirm(`是否删除【${data.name}】菜单`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
this.$http({
url: this.$http.adornUrl("/product/category/delete"),
method: "post",
data: this.$http.adornData(ids, false),
}).then(({ data }) => {
this.$message({
message: "删除成功",
type: "success",
});
//刷新出新的菜单
this.getMenus();
//设置默认展开的菜单
this.expandedKey = [node.parent.data.catId];
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
});
});
},
// 新增 / 修改
addOrUpdateHandle(id) {
this.addOrUpdateVisible = true;
this.$nextTick(() => {
this.$refs.addOrUpdate.init(id);
});
},
},
};
</script>
<style lang="scss" scoped>
</style>
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("product:category:save")
public R save(@RequestBody CategoryEntity category){
categoryService.save(category);
return R.ok();
}
/**
* 批量修改
*/
@RequestMapping("/update/sort")
//@RequiresPermissions("product:category:update")
public R updateSort(@RequestBody CategoryEntity[] category){
categoryService.updateBatchById(Arrays.asList(category));
return R.ok();
}