✅P74_属性分组-分组修改-级联选择器修改

gong_yz大约 7 分钟谷粒商城

分类属性组修改

点击修改分类属性组“修改”按钮后,发现所属分类没有回显出数据,

逻辑分析

点击修改,触发addOrUpdateHandle()函数,

将addOrUpdateVisible设置为true,即启用对话框,

this.$nextTick:对话框渲染完成之后去调用当前vue实例中导入的AddOrUpdates组件的init方法

        // 新增 / 修改
        addOrUpdateHandle(id) {
            //启用对话框
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.AddOrUpdates.init(id)
            })
        },

src\views\modules\product\attrgroup-add-or-update.vue

对话框回显所属分类,需从后台获取到对应的路径,包括父子的三级分类id。将catelogIds全部替换成catelogPath ,用于存储分类id

    init(id) {
      this.dataForm.attrGroupId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.attrGroupId) {
          this.$http({
            url: this.$http.adornUrl(`/product/attrgroup/info/${this.dataForm.attrGroupId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.attrGroupName = data.attrGroup.attrGroupName
              this.dataForm.sort = data.attrGroup.sort
              this.dataForm.descript = data.attrGroup.descript
              this.dataForm.icon = data.attrGroup.icon
              this.dataForm.catelogId = data.attrGroup.catelogId
              this.dataForm.catelogPath = data.attrGroup.catelogPath  //存储回显分类id
            }
          })
        }
      })
    },

调用后台

实体类中定义catelogPath

cfmall-product/src/main/java/com/gyz/cfmall/product/entity/AttrGroupEntity.java

    /**
     * 所属分类路径
     */
    @TableField(exist = false)
    private Long[] catelogPath;

cfmall-product/src/main/java/com/gyz/cfmall/product/controller/AttrGroupController.java

    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;

	/**
     * 信息
     */
    @RequestMapping("/info/{attrGroupId}")
    public R info(@PathVariable("attrGroupId") Long attrGroupId) {
        AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);

        Long catelogId = attrGroup.getCatelogId();
        //查询出catelogId完整路径
        Long[] catelogPaths = categoryService.findCatelogPath(catelogId);
        attrGroup.setCatelogPath(catelogPaths);
        return R.ok().put("attrGroup", attrGroup);
    }

cfmall-product/src/main/java/com/gyz/cfmall/product/service/impl/CategoryServiceImpl.java

    /**
     * @param catelogId :
     * @return java.lang.Long[]
     * @Description 查询catelogId完整路径
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //逆序
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);

        //根据当前分类id查询信息
        CategoryEntity byId = this.getById(catelogId);
        //如果当前不是父分类
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }

        return paths;
    }

页面效果

新增弹窗问题

所属分类回显数据

点击新增时,“所属分类”还保留着上次的回显,这里应该置空

参考:Dialog对话框->Events

具体实现:新增@closed事件,

//src\views\modules\product\attrgroup-add-or-update.vue
<el-dialog 
      :title="!dataForm.attrGroupId ? '新增' : '修改'" 
      :close-on-click-modal="false" 
      :visible.sync="visible" 
      @closed="dialogClosed">... </el-dialog>
 methods{
 	//新增对话框所属分类初始值为空
    dialogClosed(){
      this.dataForm.catelogPath=[];
    }
 }

可搜索功能

参考:

具体实现:

      <el-form-item label="所属分类" prop="catelogId">
        <el-cascader v-model="dataForm.catelogPath" 
          :options="categories" 
          :props="props"
          placeholder="试试搜索:手机"
          filterable
          >
        </el-cascader>
      </el-form-item>

页面效果:


完整前端代码

attrgroup.vue

src\views\modules\product\attrgroup.vue

<template>
    <el-row :gutter="20">
        <el-col :span="6">
            <category @node-click="treeNodeClick"></category>
        </el-col>
        <el-col :span="18">
            <div class="mod-config">
                <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
                    <el-form-item>
                        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="getDataList()">查询</el-button>
                        <el-button v-if="isAuth('product:attrgroup:save')" type="primary"
                            @click="addOrUpdateHandle()">新增</el-button>
                        <el-button v-if="isAuth('product:attrgroup:delete')" type="danger" @click="deleteHandle()"
                            :disabled="dataListSelections.length <= 0">批量删除</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
                    style="width: 100%;">
                    <el-table-column type="selection" header-align="center" align="center" width="50">
                    </el-table-column>
                    <el-table-column prop="attrGroupId" header-align="center" align="center" label="分组id">
                    </el-table-column>
                    <el-table-column prop="attrGroupName" header-align="center" align="center" label="组名">
                    </el-table-column>
                    <el-table-column prop="sort" header-align="center" align="center" label="排序">
                    </el-table-column>
                    <el-table-column prop="descript" header-align="center" align="center" label="描述">
                    </el-table-column>
                    <el-table-column prop="icon" header-align="center" align="center" label="组图标">
                    </el-table-column>
                    <el-table-column prop="catelogId" header-align="center" align="center" label="所属分类id">
                    </el-table-column>
                    <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small"
                                @click="addOrUpdateHandle(scope.row.attrGroupId)">修改</el-button>
                            <el-button type="text" size="small" @click="deleteHandle(scope.row.attrGroupId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                    :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
                    layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
                <!-- 弹窗, 新增 / 修改 -->
                <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
                <AddOrUpdates v-if="addOrUpdateVisible" ref="AddOrUpdates" @refreshDataList="getDataList"></AddOrUpdates>
            </div>
        </el-col>
    </el-row>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
import Category from '../common/category.vue';
import AddOrUpdates from './attrgroup-add-or-update.vue';

export default {
    //import引入的组件需要注入到对象中才能使用
    components: { Category, AddOrUpdates },
    props: {},
    data() {
        //这里存放数据
        return {
            catId: 0,
            dataForm: {
                key: ''
            },
            dataList: [],
            pageIndex: 1,
            pageSize: 10,
            totalPage: 0,
            dataListLoading: false,
            dataListSelections: [],
            addOrUpdateVisible: false
        };
    },

    //方法集合
    methods: {

        //子组件传给父组件的参数
        treeNodeClick(data, node, component) {
            console.log("父组件接收到子组件传递过来的数据为:", data, node, component);
            if (node.level == 3) {
                this.catId = data.catId;
                this.getDataList();
            }
        },

        // 获取数据列表
        getDataList() {
            this.dataListLoading = true
            this.$http({
                url: this.$http.adornUrl(`/product/attrgroup/list/${this.catId}`),
                method: 'get',
                params: this.$http.adornParams({
                    'page': this.pageIndex,
                    'limit': this.pageSize,
                    'key': this.dataForm.key
                })
            }).then(({ data }) => {
                if (data && data.code === 0) {
                    this.dataList = data.page.list
                    this.totalPage = data.page.totalCount
                } else {
                    this.dataList = []
                    this.totalPage = 0
                }
                this.dataListLoading = false
            })
        },
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val
            this.pageIndex = 1
            this.getDataList()
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val
            this.getDataList()
        },
        // 多选
        selectionChangeHandle(val) {
            this.dataListSelections = val
        },
        // 新增 / 修改
        addOrUpdateHandle(id) {
            //启用对话框
            this.addOrUpdateVisible = true
            this.$nextTick(() => {
                this.$refs.AddOrUpdates.init(id)
            })
        },
        // 删除
        deleteHandle(id) {
            var ids = id ? [id] : this.dataListSelections.map(item => {
                return item.attrGroupId
            })
            this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl('/product/attrgroup/delete'),
                    method: 'post',
                    data: this.$http.adornData(ids, false)
                }).then(({ data }) => {
                    if (data && data.code === 0) {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.getDataList()
                            }
                        })
                    } else {
                        this.$message.error(data.msg)
                    }
                })
            })
        }
    },
    //生命周期 - 创建完成(可以访问当前this实例)
    created() {
        this.getDataList();
    },
}
</script>
<style  scoped></style>

attrgroup-add-or-update.vue

src\views\modules\product\attrgroup-add-or-update.vue

<template>
  <el-dialog 
      :title="!dataForm.attrGroupId ? '新增' : '修改'" 
      :close-on-click-modal="false" 
      :visible.sync="visible" 
      @closed="dialogClosed">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="组名" prop="attrGroupName">
        <el-input v-model="dataForm.attrGroupName" placeholder="组名"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="描述"></el-input>
      </el-form-item>
      <el-form-item label="组图标" prop="icon">
        <el-input v-model="dataForm.icon" placeholder="组图标"></el-input>
      </el-form-item>
      <el-form-item label="所属分类" prop="catelogId">
        <el-cascader v-model="dataForm.catelogPath" 
          :options="categories" 
          :props="props"
          placeholder="试试搜索:手机"
          filterable
          >
        </el-cascader>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      categories: [], //:options="categories",options属性指定选项数组即可渲染出一个级联选择器
      props: {
        value: "catId", //指定选项的值为选项对象的某个属性值
        label: "name",  //指定选项标签为选项对象的某个属性值(页面分类数据category对象的name字段)
        children: "children" //指定选项的子选项为选项对象的某个属性值(页面分类数据category对象的children)
      },

      visible: false,
      dataForm: {
        attrGroupId: 0,
        attrGroupName: '',
        sort: '',
        descript: '',
        icon: '',
        catelogId: 0,
        catelogPath: [], //保存父节点和子节点的id
      },
      dataRule: {
        attrGroupName: [
          { required: true, message: '组名不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        descript: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '组图标不能为空', trigger: 'blur' }
        ],
        catelogId: [
          { required: true, message: '所属分类id不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.attrGroupId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.attrGroupId) {
          this.$http({
            url: this.$http.adornUrl(`/product/attrgroup/info/${this.dataForm.attrGroupId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.attrGroupName = data.attrGroup.attrGroupName
              this.dataForm.sort = data.attrGroup.sort
              this.dataForm.descript = data.attrGroup.descript
              this.dataForm.icon = data.attrGroup.icon
              this.dataForm.catelogId = data.attrGroup.catelogId
              this.dataForm.catelogPath = data.attrGroup.catelogPath
            }
          })
        }
      })
    },

    // 表单提交
    dataFormSubmit() {
      console.log("表单提交获取到的分类数据为:", this.dataForm);
      console.log("截取出来的catelogId:", this.dataForm.catelogPath[this.dataForm.catelogPath.length - 1]);
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/product/attrgroup/${!this.dataForm.attrGroupId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              attrGroupId: this.dataForm.attrGroupId || undefined,
              attrGroupName: this.dataForm.attrGroupName,
              sort: this.dataForm.sort,
              descript: this.dataForm.descript,
              icon: this.dataForm.icon,
              catelogId: this.dataForm.catelogPath[this.dataForm.catelogPath.length - 1]
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    getCategories() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        console.log("获取三级分类数据:", data);
        this.categories = data.data;
      });
    },

    //新增对话框所属分类初始值为空
    dialogClosed(){
      this.dataForm.catelogPath=[];
    }

  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
    this.getCategories();
  },
}
</script>