1.三级分类

1.1树型展示三级分类数据

1.1.1需求分析

  • 流程分析
    code
  • pms_category表
    code

    1.1.2后端实现

  1. CategoryController
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Autowired
    private CategoryService categoryService;

    /**
    * 查出所有分类以及子分类,以树型结构组装起来
    */
    @RequestMapping("/list/tree")
    //@RequiresPermissions("product:category:list")
    public R list(){
    List<CategoryEntity> entities = categoryService.listWithTree();

    return R.ok().put("data", entities);
    }
  2. 在CategoryEntity中添加
    1
    2
    @TableField(exist = false)
    private List<CategoryEntity> children;
  3. CategoryService
    1
    2
    //获取三级分类的方法
    List<CategoryEntity> listWithTree();
  1. CategoryServiceImpl
    • 找到所有的分类
    • 根据分类过滤出所有根节点
    • 设置子节点为 — getchildren(过滤出的根节点,所有节点)
      • 根据所有节点进行过滤 — 所有节点的partentCid等于根节点的catid
      • 对过滤出的节点进行递归
      • 进行排序 — 注意返回结果为null
      • 进行收集
    • 进行排序
    • 进行收集
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Override
public List<CategoryEntity> listWithTree() {
//1.查出所有分类
List<CategoryEntity> entities = baseMapper.selectList(null);
//2.组装成父子的树型结构
List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == 0;
}).map((menu)->{
menu.setChildren(getChildrens(menu,entities));
return menu;
}).sorted((menu1,menu2)->{
return menu1.getSort() - menu2.getSort();
}).collect(Collectors.toList());

return level1Menus;
}

//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid() == root.getCatId();
}).map((categoryEntity)->{
//1.找到子菜单
categoryEntity.setChildren(getChildrens(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.1.3配置网关路由及路径重写

  1. 设置前端路由
    • 在src/static/config/index.js修改
      向后台发送请求时,会把前面的地址改为http://localhost:88/api
      1
      2
        // api接口请求地址
      window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api';
  2. 对renren-fast进行注册
  3. 修改gateway模块的yaml文件
    • id为标识
      • uri表示满足特定要求时,请求将被转发到renren-fast服务,lb是负载均衡
      • predicates表示以/api/开头时,这个路由会被触发
      • filters是一个过滤列表,它的作用是重写请求的路径,将路径中的/api/替换为/renren-fast/
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        spring:
        cloud:
        gateway:
        routes:
        - id: admin_route
        uri: lb://renren-fast
        predicates:
        - Path=/api/**
        filters:
        - RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}

1.1.4网关统一配置跨域

  • 跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。
  • 同源策略:是指协议,域名,端口都要相同,其中有一个不同都会产生跨域;
  • 官方文档https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
    code
  • 解决方法:

    1. 使用nagix跨域代理
      code
    2. 配置当次请求允许跨域
    • 添加响应头
      • Access-Control-Allow-Origin:支持哪些来源的请求跨域
      • Access-Control-Allow-Methods:支持哪些方法跨域
      • Access-Control-Allow-Credentials:跨域请求默认不包含cookie,设置为true可以包含cookie
      • Access-Control-Expose-Headers:跨域请求暴露的字段
      • CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。
      • Access-Control-Max-Age:表明该响应的有效时间为多少秒。在有效时间内,浏览器无须为同一请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。
  • 实现

    1. 在gateway模块中创建GulimallCorsConfiguration
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      package com.atguigu.gulimall.gateway.config;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.cors.CorsConfiguration;
      import org.springframework.web.cors.reactive.CorsWebFilter;
      import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

      @Configuration
      public class GulimallCorsConfiguration {
      @Bean
      public CorsWebFilter corsWebFilter(){

      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      CorsConfiguration corsConfiguration = new CorsConfiguration();

      //配置跨域
      corsConfiguration.addAllowedHeader("*");
      corsConfiguration.addAllowedMethod("*");
      corsConfiguration.addAllowedOrigin("*");
      corsConfiguration.setAllowCredentials(true);

      source.registerCorsConfiguration("/**",corsConfiguration);
      return new CorsWebFilter(source);
      }
      }
    2. 注释掉renren-fast自带的跨域配置

1.1.5前端实现

配置路由

code

  1. 把product注册到配置中心
  2. 创建一级菜单
    code
  3. 在一级菜单里面添加商品维护
    code
  4. 商品维护的路由
    • 这个页面的位置就在src/views/modules/product/category.vue
      code
  5. 修改src/views/modules/product/category.vue页面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    <template>
    <div>
    <el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
    </div>
    </template>

    <script>

    export default {
    components: {},
    props: {},
    data() {
    return {
    menus: [],
    defaultProps: {
    children: 'children',
    label: 'name'
    }
    };
    },
    methods: {
    handleNodeClick(data) {
    console.log(data);
    },
    getMenus(){
    this.$http({
    url: this.$http.adornUrl('/product/category/list/tree'),
    method: 'get',
    }).then(({data})=>{
    console.log("成功获取到菜单数据...",data.data)
    this.menus = data.data
    })
    }
    },
    created() {
    this.getMenus();
    },
    }
    </script>
    <style scoped></style>
  6. 结果显示
    code

1.2 数据删除

1.2.1 前端页面修改

  • 修改src/views/modules/product/category.vue
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    <template>
    <div>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId">
    <span class="custom-tree-node" slot-scope="{ node, data }">
    <span>{{ node.label }}</span>
    <span>
    <el-button v-if="node.level <=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>
    </span>
    </span>
    </el-tree>
    </div>
    </template>

    <script>

    export default {
    components: {},
    props: {},
    data() {
    return {
    menus: [],
    defaultProps: {
    children: 'children',
    label: 'name'
    }
    };
    },
    methods: {

    getMenus() {
    this.$http({
    url: this.$http.adornUrl('/product/category/list/tree'),
    method: 'get',
    }).then(({ data }) => {
    console.log("成功获取到菜单数据...", data.data)
    this.menus = data.data
    })
    },

    append(data) {
    console.log("append",data);
    },
    remove(node, data) {
    console.log("remove",node,data);
    },
    },
    created() {
    this.getMenus();
    },
    }
    </script>
    <style scoped></style>
    code

1.2.2 后端逻辑删除

  • 逻辑删除 — show_status
  1. CategoryController
    1
    2
    3
    4
    5
    6
    7
    8
    9
    //删除数据
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
    //检查当前删除的菜单是否被别的地方引用
    categoryService.removeMenuByIds(Arrays.asList(catIds));

    //categoryService.removeByIds(Arrays.asList(catIds));
    return R.ok();
    }
  2. CategoryService
    1
    void removeMenuByIds(List<Long> asList);
  3. CategoryServiceImpl
    1
    2
    3
    4
    5
    6
    7
    8
      //数据删除
    @Override
    public void removeMenuByIds(List<Long> asList) {
    //todo: 1.检查当前删除的菜单,是否被别的地方引用

    //逻辑删除
    baseMapper.deleteBatchIds(asList);
    }
    • 配置全局逻辑配置规则(可省略)
      1
      2
      3
      4
      5
      6
      7
      mybatis-plus:
      mapper-locations: classpath:/mspper/**/*.xml
      global-config:
      db-config:
      id-type: auto
      logic-delete-value: 1
      logic-not-delete-value: 0
    • 给实体类添加逻辑删除注解@TableLogic
      1
      2
      @TableLogic(value = "1",delval = "0")
      private Integer showStatus;

      1.2.3前端效果细化

    • 添加了删除弹框提示和展开及成功消息
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      <template>
      <div>
      <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
      :default-expanded-keys="expandedKey">
      <span class="custom-tree-node" slot-scope="{ node, data }">
      <span>{{ node.label }}</span>
      <span>
      <el-button v-if="node.level <= 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>
      </span>
      </span>
      </el-tree>
      </div>
      </template>

      <script>

      export default {
      components: {},
      props: {},
      data() {
      return {
      menus: [],
      expandedKey: [],
      defaultProps: {
      children: 'children',
      label: 'name'
      }
      };
      },
      methods: {

      getMenus() {
      this.$http({
      url: this.$http.adornUrl('/product/category/list/tree'),
      method: 'get',
      }).then(({ data }) => {
      console.log("成功获取到菜单数据...", data.data)
      this.menus = data.data
      })
      },

      append(data) {
      console.log("append", data);
      },

      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(() => {

      });
      console.log("remove", node, data);
      }
      },
      created() {
      this.getMenus();
      },
      }
      </script>
      <style scoped></style>

1.3 数据添加

1.3.1 前端页面修改

  • 效果演示
    • 点击添加出现表单
      code
  • category.vue
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    <template>
    <div>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
    :default-expanded-keys="expandedKey">
    <span class="custom-tree-node" slot-scope="{ node, data }">
    <span>{{ node.label }}</span>
    <span>
    <el-button v-if="node.level <= 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>
    </span>
    </span>
    </el-tree>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
    <el-form :model="categroy">
    <el-form-item label="分类名称">
    <el-input v-model="categroy.name" 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="addCategory">确 定</el-button>
    </span>
    </el-dialog>
    </div>
    </template>

    <script>

    export default {
    components: {},
    props: {},
    props: {},
    data() {
    return {
    title: ''
    categroy: { name: '', parentCid: 0, catLevel: 0, showStatus: 1, sort: 0 },
    dialogVisible: false,
    menus: [],
    expandedKey: [],
    defaultProps: {
    children: 'children',
    label: 'name'
    }
    };
    },
    methods: {

    getMenus() {
    this.$http({
    url: this.$http.adornUrl('/product/category/list/tree'),
    method: 'get',
    }).then(({ data }) => {
    console.log("成功获取到菜单数据...", data.data)
    this.menus = data.data
    })
    },

    append(data) {
    console.log("append", data);
    this.dialogVisible = true;
    this.categroy.parentCid = data.catId;
    this.categroy.catLevel = data.catLevel * 1 + 1;
    },

    //添加三级分类
    addCategory() {
    this.$http({
    url: this.$http.adornUrl('/product/category/save'),
    method: 'post',
    data: this.$http.adornData(this.categroy, false)
    }).then(({ data }) => {
    this.$message({
    message: '菜单保存成功',
    type: 'success'
    });
    //关闭对话框
    this.dialogVisible = false;
    //刷新出新的菜单
    this.getMenus();
    //设置需要默认展开的菜单
    this.expandedKey = [this.categroy.parentCid]
    })

    console.log("提交的三级分类数据", this.categroy)

    },

    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(() => {

    });

    console.log("remove", node, data);
    }

    },

    created() {
    this.getMenus();
    },
    }
    </script>
    <style scoped></style>

1.3.2 后端实现—-renren-fast自带

  • CategoryController
    1
    2
    3
    4
    5
    6
    7
      //保存
    @RequestMapping("/save")
    // @RequiresPermissions("product:category:save")
    public R save(@RequestBody CategoryEntity category){
    categoryService.save(category);
    return R.ok();
    }

1.4数据修改

1.4.1 前端页面修改

  • 添加修改的页面,数据回显
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    <template>
    <div>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="catId"
    :default-expanded-keys="expandedKey">
    <span class="custom-tree-node" slot-scope="{ node, data }">
    <span>{{ node.label }}</span>
    <span>
    <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">添加</el-button>
    <el-button type="text" size="mini" @click="edit(data)">修改</el-button>
    <el-button v-if="node.childNodes.length == 0" type="text" size="mini"
    @click="() => remove(node, data)">删除</el-button>

    </span>
    </span>
    </el-tree>

    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
    <el-form :model="categroy">
    <el-form-item label="分类名称">
    <el-input v-model="categroy.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="图标">
    <el-input v-model="categroy.icon" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="计量单位">
    <el-input v-model="categroy.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="submit">确 定</el-button>
    </span>
    </el-dialog>
    </div>
    </template>

    <script>

    export default {
    components: {},
    props: {},
    props: {},
    data() {
    return {
    title: "",
    dialogType: "",
    categroy: {
    name: '',
    parentCid: 0,
    catLevel: 0,
    showStatus: 1,
    sort: 0,
    catId: null,
    productUnit: '',
    icon: '',
    },
    dialogVisible: false,
    menus: [],
    expandedKey: [],
    defaultProps: {
    children: 'children',
    label: 'name'
    }
    };
    },
    methods: {

    getMenus() {
    this.$http({
    url: this.$http.adornUrl('/product/category/list/tree'),
    method: 'get',
    }).then(({ data }) => {
    console.log("成功获取到菜单数据...", data.data)
    this.menus = data.data
    })
    },

    edit(data) {
    console.log("要修改的数据", data)
    this.dialogType = "edit"
    this.title = "修改分类"
    this.dialogVisible = true
    //发送请求获取当前节点最新的数据
    this.$http({
    url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
    method: 'get',
    }).then(({ data }) => {
    //请求成功
    console.log("要回显的数据", data)
    this.categroy.name = data.data.name
    this.categroy.catId = data.data.catId
    this.categroy.icon = data.data.icon
    this.categroy.productUnit = data.data.productUnit
    this.categroy.parentCid = data.data.productUnit
    this.categroy.catLevel = data.data.Catlevel
    this.categroy.sort = data.data.sort
    this.categroy.showStatus = data.data.showStatus
    })
    },

    append(data) {
    console.log("append", data);
    this.dialogType = "add"
    this.title = "添加分类"
    this.dialogVisible = true;
    this.categroy.parentCid = data.catId;
    this.categroy.catLevel = data.catLevel * 1 + 1;
    this.categroy.catId = null
    this.categroy.icon = ""
    this.categroy.name = ""
    this.categroy.productUnit = ""
    this.categroy.sort = 0
    this.categroy.showStatus = 1
    },

    submit() {
    if (this.dialogType == "add") {
    this.addCategory();
    }
    if (this.dialogType == "edit") {
    this.editCategory();
    }
    },

    //修改三级分类数据
    editCategory() {
    var { name, catId, icon, productUnit } = this.categroy;
    this.$http({
    url: this.$http.adornUrl('/product/category/update'),
    method: 'post',
    data: this.$http.adornData({ catId, name, icon, productUnit }, false)
    }).then(({ data }) => {
    this.$message({
    message: '菜单保存成功',
    type: 'success'
    });
    //关闭对话框
    this.dialogVisible = false;
    //刷新出新的菜单
    this.getMenus();
    //设置需要默认展开的菜单
    this.expandedKey = [this.categroy.parentCid]
    })
    },

    //添加三级分类
    addCategory() {
    this.$http({
    url: this.$http.adornUrl('/product/category/save'),
    method: 'post',
    data: this.$http.adornData(this.categroy, false)
    }).then(({ data }) => {
    this.$message({
    message: '菜单保存成功',
    type: 'success'
    });
    //关闭对话框
    this.dialogVisible = false;
    //刷新出新的菜单
    this.getMenus();
    //设置需要默认展开的菜单
    this.expandedKey = [this.categroy.parentCid]
    })
    console.log("提交的三级分类数据", this.categroy)

    },

    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(() => {
    });
    console.log("remove", node, data);
    }
    },
    created() {
    this.getMenus();
    },

    }
    </script>
    <style scoped></style>

    1.4.2 后端由renren-fast自带

  • CategoryController
    1
    2
    3
    4
    5
    6
    7
      @RequestMapping("/update")
    //@RequiresPermissions("product:category:update")
    public R update(@RequestBody CategoryEntity category){
    categoryService.updateById(category);

    return R.ok();
    }

1.5 菜单拖拽功能

1.5.1前端实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<template>
<div>
<el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
<el-button v-if="draggable" @click="batchSave">批量保存</el-button>
<el-button type="danger" @click="batchDelete">批量删除</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="node.level <=2"
type="text"
size="mini"
@click="() => append(data)"
>Append</el-button>
<el-button type="text" size="mini" @click="edit(data)">edit</el-button>
<el-button
v-if="node.childNodes.length==0"
type="text"
size="mini"
@click="() => remove(node, data)"
>Delete</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>

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
props: {},
data() {
return {
pCid: [],
draggable: false,
updateNodes: [],
maxLevel: 0,
title: "",
dialogType: "", //edit,add
category: {
name: "",
parentCid: 0,
catLevel: 0,
showStatus: 1,
sort: 0,
productUnit: "",
icon: "",
catId: null
},
dialogVisible: false,
menus: [],
expandedKey: [],
defaultProps: {
children: "children",
label: "name"
}
};
},

//计算属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
getMenus() {
this.$http({
url: this.$http.adornUrl("/product/category/list/tree"),
method: "get"
}).then(({ data }) => {
console.log("成功获取到菜单数据...", data.data);
this.menus = data.data;
});
},
batchDelete() {
let catIds = [];
let checkedNodes = this.$refs.menuTree.getCheckedNodes();
console.log("被选中的元素", checkedNodes);
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(() => {});
},
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 = 0;
});
},
handleDrop(draggingNode, dropNode, dropType, ev) {
console.log("handleDrop: ", 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;
}
this.pCid.push(pCid);

//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 });
}
}

//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);
//
this.countNodeLevel(draggingNode);
//当前正在拖动的节点+父节点所在的深度不大于3即可
let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
console.log("深度:", deep);

// this.maxLevel
if (type == "inner") {
// console.log(
// `this.maxLevel:${this.maxLevel};draggingNode.data.catLevel:${draggingNode.data.catLevel};dropNode.level:${dropNode.level}`
// );
return deep + dropNode.level <= 3;
} else {
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) {
console.log("要修改的数据", data);
this.dialogType = "edit";
this.title = "修改分类";
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;
/**
* parentCid: 0,
catLevel: 0,
showStatus: 1,
sort: 0,
*/
});
},
append(data) {
console.log("append", data);
this.dialogType = "add";
this.title = "添加分类";
this.dialogVisible = true;
this.category.parentCid = data.catId;
this.category.catLevel = data.catLevel * 1 + 1;
this.category.catId = null;
this.category.name = "";
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;
this.$http({
url: this.$http.adornUrl("/product/category/update"),
method: "post",
data: this.$http.adornData({ catId, name, icon, productUnit }, 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(() => {});
console.log("remove", node, data);
}
},
//生命周期 - 创建完成(可以访问当前this实例)
created() {
this.getMenus();
},
};
</script>
<style scoped>
</style>

1.5.2后端实现

  • 其余由renren-fast自带
    1
    2
    3
    4
    5
    6
    7
    //批量修改分类
    @RequestMapping("/update/sort")
    //@RequiresPermissions("product:category:update")
    public R update(@RequestBody CategoryEntity[] category){
    categoryService.updateBatchById(Arrays.asList(category));
    return R.ok();
    }

    1.6总结

  • 这一章节除了分类的查询,其余基本都是在编写前端,后端基本是自带的。
  • 这一章节的前端页面是自己编写的,后面的功能直接使用逆向生成的代码

2.品牌管理

2.1使用逆向工程前端代码

2.1.1 快速生成

  • 在前端页面添加品牌管理
    code
  • 把后端代码里面的vue文件拷贝到前端里面
  • 运行效果如下

    列表上面的文字是由数据库注释决定的
    里面没有添加,删除按钮是因为权限问题
    在index.js里面,把isAuth函数的返回值改为true即可

code

2.1.2优化效果

  • 把显示状态改为按钮