Springboot3 + MyBatis-Plus + MySql + Vue + ProTable + TS 实现后台管理商品分类(最新教程附源码)

Springboot3 + MyBatis-Plus + MySql + Uniapp 商品加入购物车功能实现(针对上一篇sku)

  • 1、效果展示
  • 2、数据库设计
  • 3、后端源码
    • 3.1 application.yml 方便 AliOssUtil.java 读取
    • 3.2 model 层
    • 3.2.1 BaseEntity
    • 3.2.1 GoodsType
    • 3.2.3 GoodsTypeSonVo
    • 3.3 Controller 层
      • 3.3.1 FileUploadController.java 后端上传图片到阿里云OSS
      • 3.3.2 AliOssUtil.java 后端上传图片到阿里云OSS的工具类
      • 3.3.3 GoodsTypeController.java 商品分类接口
    • 3.4 GoodsTypeService 层
    • 3.5 GoodsTypeServiceImpl 层
  • 4、前端代码
    • 4.1 type.Vue
    • 4.2 type.Vue
    • 4.3 addOrEditType.Vue
    • 4.4 supportTypeDialog.Vue

1、效果展示


QQ2024930-15058

在这里插入图片描述

2、数据库设计


/*Navicat Premium Data TransferSource Server         : Test1Source Server Type    : MySQLSource Server Version : 80200Source Host           : localhost:3306Source Schema         : yunshangshequTarget Server Type    : MySQLTarget Server Version : 80200File Encoding         : 65001Date: 30/09/2024 15:08:28
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for goods_type
-- ----------------------------
DROP TABLE IF EXISTS `goods_type`;
CREATE TABLE `goods_type`  (`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类名称',`description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类描述',`img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '分类图标',`father_id` int NULL DEFAULT NULL COMMENT '如果没有 father_id 则是一级分类',`status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '是否启用 1 启用 0禁用',`type_sort` int NULL DEFAULT NULL COMMENT '排序',`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',`is_deleted` tinyint NULL DEFAULT NULL COMMENT '逻辑删除',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of goods_type
-- ----------------------------
INSERT INTO `goods_type` VALUES (1, '水果', '所有水果哈哈哈', 'https://yunshangshequ.cn-chengdu.oss.aliyuncs.com/2024.09.30/b648e907-12e1-406d-89cd-d4948b3ed317.png', NULL, '1', 999, NULL, '2024-09-30 15:01:39', 0);
INSERT INTO `goods_type` VALUES (2, '零食', '所有零食', NULL, NULL, '1', 9999, NULL, '2024-09-30 14:48:53', 0);
INSERT INTO `goods_type` VALUES (3, '西瓜', '非常好吃的西瓜', 'https://yunshangshequ.oss-cn-chengdu.aliyuncs.com/icons/icon_3212wanjasr/xiguarang.png', 1, '1', 999999, NULL, '2024-09-30 14:42:36', 0);
INSERT INTO `goods_type` VALUES (4, '葡萄', '非常好吃的葡萄', 'https://yunshangshequ.oss-cn-chengdu.aliyuncs.com/icons/icon_3212wanjasr/putao.png', 1, '1', 20, NULL, NULL, 0);
INSERT INTO `goods_type` VALUES (5, '芒果', '非常好吃的芒果12', 'https://yunshangshequ.oss-cn-chengdu.aliyuncs.com/icons/icon_3212wanjasr/mangguo.png', 1, '1', 5, NULL, '2024-09-30 15:01:17', 1);
INSERT INTO `goods_type` VALUES (6, '坚果', '非常好吃的坚果', NULL, 2, '1', 100, NULL, NULL, 0);
INSERT INTO `goods_type` VALUES (7, '辣条', '非常好吃的辣条', NULL, 2, '1', 20, NULL, NULL, 0);
INSERT INTO `goods_type` VALUES (10, '橘子', '非常好吃的橘子', 'https://yunshangshequ.oss-cn-chengdu.aliyuncs.com/icons/icon_3212wanjasr/juzi.png', 1, '1', 999, '2024-09-30 13:49:02', '2024-09-30 14:36:23', 0);
INSERT INTO `goods_type` VALUES (11, '香蕉', '非常非常好吃的香蕉', 'https://yunshangshequ.cn-chengdu.oss.aliyuncs.com/2024.09.30/404a678d-aae3-4e5b-844f-ba27643d9209.png', 1, '1', 2222, '2024-09-30 13:57:13', '2024-09-30 14:38:53', 1);
INSERT INTO `goods_type` VALUES (12, '火龙果', '非常好吃的火龙果', 'https://yunshangshequ.cn-chengdu.oss.aliyuncs.com/2024.09.30/3c18869e-f0bb-48a7-8c3e-8fd02318bfd5.png', 1, '1', 99999, '2024-09-30 13:58:54', '2024-09-30 14:25:13', 1);
INSERT INTO `goods_type` VALUES (13, '芒果', '非常好吃的芒果', 'https://yunshangshequ.cn-chengdu.oss.aliyuncs.com/2024.09.30/928d56f0-7062-4eaf-a89b-52ba43199322.png', 1, '1', 9999999, '2024-09-30 15:01:33', NULL, 0);SET FOREIGN_KEY_CHECKS = 1;

3、后端源码

3.1 application.yml 方便 AliOssUtil.java 读取

server:port: 8080
spring:servlet:multipart:max-file-size: 40MBmax-request-size: 40MBdatasource:type: com.zaxxer.hikari.HikariDataSourceurl: jdbc:mysql://localhost:3306/yunshangshequ?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2b8username: rootpassword: 123456hikari:connection-test-query: SELECT 1 # 自动检测连接connection-timeout: 60000 #数据库连接超时时间,默认30秒idle-timeout: 500000 #空闲连接存活最大时间,默认600000(10分钟)max-lifetime: 540000 #此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟maximum-pool-size: 12 #连接池最大连接数,默认是10minimum-idle: 10 #最小空闲连接数量pool-name: SPHHikariPool # 连接池名称jackson:time-zone: GMT+8data:redis:host: localhostport: 6379database: 0
#用于打印框架生成的sql语句,便于调试
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:logic-delete-field: isDeleted # 全局逻辑删除的实体字段名logic-delete-value: 1   # 逻辑已删除的值 默认为 1logic-not-delete-value: 0 # 逻辑未删除的值  默认为 0minio:endpoint: http://localhost:9000access-key: minioadminsecret-key: minioadminbucket-name: yunshangshequ
springdoc:default-flat-param-object: truealioss: # 阿里云配置endpoint: "https://cn-chengdu.oss.aliyuncs.com"    # Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。bucketName: ""  # 填写Bucket名称,例如examplebucket。access_key: ""  # 点击头像->Accesskey管理查看 秘钥access_key_secret: "" # 密码

3.2 model 层

3.2.1 BaseEntity


package com.zhong.model.entity;import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;import java.io.Serializable;
import java.util.Date;@Data
public class BaseEntity implements Serializable {@Schema(description = "主键")@TableId(value = "id", type = IdType.AUTO)private Long id;@Schema(description = "创建时间")@TableField(value = "create_time", fill = FieldFill.INSERT)@JsonIgnoreprivate Date createTime;@Schema(description = "更新时间")@TableField(value = "update_time", fill = FieldFill.UPDATE)@JsonIgnoreprivate Date updateTime;@Schema(description = "逻辑删除")@TableField("is_deleted")@JsonIgnoreprivate Byte isDeleted;}

3.2.1 GoodsType


package com.zhong.model.entity.goods;import com.zhong.model.entity.BaseEntity;
import lombok.Data;/*** 商品分类* @TableName shop_type*/
@Data
public class GoodsType extends BaseEntity {/**/*** 分类名称*/private String name;/*** 分类描述*/private String description;/*** 排序值*/private Long typeSort;/*** 分类图标*/private String img;/*** 如果没有 father_id 则是一级分类*/private Integer fatherId;/*** 是否启用 1 启用 0禁用*/private Integer status;private static final long serialVersionUID = 1L;
}

3.2.3 GoodsTypeSonVo


package com.zhong.vo.small;import com.zhong.model.entity.goods.GoodsType;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;import java.util.List;/*** @ClassName : GoodsTypeVo* @Description :* @Author : zhx* @Date: 2024-09-29 15:08*/
@Data
public class GoodsTypeSonVo {List<GoodsType> fatherType;List<GoodsType> sonType;
}

3.3 Controller 层

3.3.1 FileUploadController.java 后端上传图片到阿里云OSS


package com.zhong.controller.apartment;import com.zhong.result.Result;
import com.zhong.utils.AliOssUtil;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;@Tag(name = "文件管理")
@RequestMapping("/admin/file")
@RestController
public class FileUploadController {@Autowiredprivate AliOssUtil ossUtil;@Operation(summary = "上传文件")@PostMapping("/upload")public Result<String> upload(@RequestParam MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {// 获取文件原名String originalFilename = file.getOriginalFilename();// 防止重复上传文件名重复String fileName = null;if (originalFilename != null) {fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.indexOf("."));}// 把文件储存到本地磁盘
//        file.transferTo(new File("E:\\SpringBootBase\\ProjectOne\\big-event\\src\\main\\resources\\flies\\" + fileName));String url = ossUtil.uploadFile(fileName, file.getInputStream());System.out.println();return Result.ok(url);}
}

3.3.2 AliOssUtil.java 后端上传图片到阿里云OSS的工具类


package com.zhong.utils;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zhong.result.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;/*** @ClassName : AliOssUtil* @Description : 阿里云上传服务* @Author : zhx* @Date: 2024-03-1 20:29*/
@Component
@Service
public class AliOssUtil {@Value("${alioss.endpoint}")private String ENDPOINT;@Value("${alioss.bucketName}")private String BUCKETNAME;@Value("${alioss.access_key}")private String ACCESS_KEY;@Value("${alioss.access_key_secret}")private String ACCESS_KEY_SECRET;public String uploadFile(String objectName, InputStream inputStream) {String url = "";// 创建OSSClient实例。System.out.println(ACCESS_KEY);OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);try {// 创建PutObjectRequest对象。// 生成日期文件夹路径,例如:2022/04/18SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");String dateStr = dateFormat.format(new Date());PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, dateStr + "/" + objectName, inputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);url = "https://" + BUCKETNAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + dateStr + "/" + objectName;} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}return url;}public  Result deleteFile(String objectName) {System.out.println(objectName);// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);try {// 删除文件。System.out.println(objectName);System.out.println(objectName.replace(",", "/"));ossClient.deleteObject(BUCKETNAME, objectName.replace(",", "/"));return Result.ok("删除成功!");} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}return Result.fail(555,"上传失败!");}
}

3.3.3 GoodsTypeController.java 商品分类接口


package com.zhong.controller.small;import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhong.model.entity.enums.BaseStatus;
import com.zhong.model.entity.goods.GoodsType;
import com.zhong.result.Result;
import com.zhong.service.small.GoodsTypeService;
import com.zhong.vo.small.GoodsTypeSonVo;
import com.zhong.vo.small.GoodsTypeVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** @ClassName : ShopSpecsController* @Description :  商品分类* @Author : zhx* @Date: 2024-09-28 15:07*/
@Slf4j
@RestController
@Tag(name = "后台商品分类管理")
@RequestMapping("/admin/goods/type")
public class GoodsTypeController {@Autowiredprivate GoodsTypeService service;@Operation(summary = "分页获商品分类信息")@GetMapping("page")private Result<IPage<GoodsType>> page(@RequestParam long current, @RequestParam long size, GoodsTypeVo goodsTypeVo) {Page<GoodsType> goodsTypePage = new Page<>(current, size);Page<GoodsType> page = service.pageItem(goodsTypePage, goodsTypeVo);return Result.ok(page);}@Operation(summary = "获所有商品二级分类信息")@GetMapping("page/son")private Result<GoodsTypeSonVo> pageSon(@RequestParam long id) {GoodsTypeSonVo page = service.list(id);return Result.ok(page);}@Operation(summary = "获所有商品分类信息")@GetMapping("list")private Result<List<GoodsType>> page() {List<GoodsType> page = service.list();return Result.ok(page);}@Operation(summary = "根据ID修改商品分类")@PostMapping("saveOrUpdate")public Result saveOrUpdateType(@RequestBody GoodsType goodsType) {goodsType.setIsDeleted((byte) 0);service.saveOrUpdate(goodsType);return Result.ok();}@DeleteMapping("deleteById")@Operation(summary = "根据id删除商品分类")public Result removeById(@RequestParam Long id) {service.removeById(id);return Result.ok();}}

3.4 GoodsTypeService 层


package com.zhong.service.small;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zhong.model.entity.goods.GoodsType;
import com.zhong.vo.small.GoodsTypeSonVo;
import com.zhong.vo.small.GoodsTypeVo;import java.util.List;/**
* @author zhong
* @description 针对表【shop_type(商品分类)】的数据库操作Service
* @createDate 2024-09-15 18:18:13
*/
public interface GoodsTypeService extends IService<GoodsType> {Page<GoodsType> pageItem(Page<GoodsType> goodsTypePage, GoodsTypeVo goodsTypeVo);GoodsTypeSonVo list(long id);}

3.5 GoodsTypeServiceImpl 层


package com.zhong.service.small.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.zhong.mapper.small.GoodsTypeMapper;
import com.zhong.model.entity.goods.GoodsSku;
import com.zhong.model.entity.goods.GoodsType;
import com.zhong.service.small.GoodsTypeService;
import com.zhong.vo.small.GoodsTypeSonVo;
import com.zhong.vo.small.GoodsTypeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author zhong* @description 针对表【shop_type(商品分类)】的数据库操作Service实现* @createDate 2024-09-15 18:18:13*/
@Service
public class GoodsTypeServiceImpl extends ServiceImpl<GoodsTypeMapper, GoodsType>implements GoodsTypeService {@Autowiredprivate GoodsTypeMapper mapper;@Overridepublic Page<GoodsType> pageItem(Page<GoodsType> goodsTypePage, GoodsTypeVo goodsTypeVo) {LambdaQueryWrapper<GoodsType> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.isNull(GoodsType::getFatherId).eq(GoodsType::getIsDeleted, 0);if (goodsTypeVo.getName() != null) {queryWrapper.like(GoodsType::getName, goodsTypeVo.getName());}if (goodsTypeVo.getId() != null) {queryWrapper.like(GoodsType::getId, goodsTypeVo.getId());}queryWrapper.orderByDesc(GoodsType::getTypeSort);return mapper.selectPage(goodsTypePage, queryWrapper);}@Overridepublic GoodsTypeSonVo list(long id) {GoodsTypeSonVo goodsTypeSonVo = new GoodsTypeSonVo();// 获取父分类LambdaQueryWrapper<GoodsType> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(GoodsType::getIsDeleted, 0).eq(GoodsType::getId, id);List<GoodsType> goodsTypes = mapper.selectList(queryWrapper);goodsTypeSonVo.setFatherType(goodsTypes);// 获取子分类LambdaQueryWrapper<GoodsType> sonQueryWrapper = new LambdaQueryWrapper<>();sonQueryWrapper.eq(GoodsType::getIsDeleted, 0).eq(GoodsType::getFatherId, id).orderByDesc(GoodsType::getTypeSort);List<GoodsType> sonGoodsTypes = mapper.selectList(sonQueryWrapper);goodsTypeSonVo.setSonType(sonGoodsTypes);return goodsTypeSonVo;}
}

4、前端代码

4.1 type.Vue


<template><el-uploadv-bind="$attrs":action="UPLOAD_IMG_URL":on-preview="handlePictureCardPreview":headers="{ 'access-token': useUserStore().token }"><el-icon><Plus /></el-icon></el-upload><el-dialog v-model="dialogVisible"><el-image :src="dialogImageUrl" fit="fill" /></el-dialog>
</template>
<script setup lang="ts">
import { UPLOAD_IMG_URL } from '@/api/upload'
import { ref } from 'vue'
import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import { useUserStore } from '@/store/modules/user'const dialogImageUrl = ref('')
const dialogVisible = ref(false)
function handlePictureCardPreview(uploadFile: UploadFile) {dialogImageUrl.value = uploadFile.url!dialogVisible.value = true
}
</script>
<style scoped lang="scss"></style>

4.2 type.Vue


<template><div><ProTable ref="proTable" :dataCallback="dataCallback" :columns="columns" :requestApi="getTypeListPageApi":initParam="initParam"><template #tableHeader><el-button type="primary" icon="Plus" @click="addHandle">添加</el-button></template><!-- 表格操作 --><template #operation="scope"><el-button type="primary" link icon="Edit" @click="editHandle(scope.row)">编辑</el-button><el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button></template></ProTable><PostDialog ref="DialogRef" /></div>
</template><script setup lang="tsx">
import { reactive, ref } from 'vue'
import { ColumnProps } from '@/components/ProTable/src/types'
import { useHandleData } from '@/hooks/useHandleData'
import { useRouter } from 'vue-router'
const router = useRouter();
import {getTypeListPageApi,// addGoodsTypeApi,// // updateGoodsTypeStatusApi,// updateGoodsTypeApi
} from '@/api/goodsType'import { PostInterfacesRes } from '@/api/goodsType/types'// *获取 ProTable 元素,调用其获取刷新数据方法
const proTable = ref()// *查询参数
const initParam = reactive({})// 处理返回的数据格式
const dataCallback = (data: any) => {return {list: data?.records,total: data?.total,}
}// 新增商品
// 新增
const addHandle = () => {router.push({path: '/small/type/addOrEditGoods',})
}
// 查看
const editHandle = (row: PostInterfacesRes) => {console.log(row)router.push({path: '/small/type/addOrEditGoods',query: {id: row.id,},})
}
// *根据id删除用户
const handleDelete = async (row: PostInterfacesRes) => {// await useHandleData(deleteSysPostById, row.id, `删除${row.id}`)proTable.value?.getTableList()
}// *表格配置项
const columns: ColumnProps[] = [{ type: 'index', label: '序号', width: 100 },{prop: 'id',label: '分类ID',search: { el: 'input', props: { placeholder: '请输入分类编码' } },},{prop: 'name',label: '分类名称',search: { el: 'input', props: { placeholder: '请输入分类名称' } },},{prop: 'description',label: '分类描述',},{prop: 'typeSort',label: '分类排序',},{prop: 'status',label: '状态',width: 100,enum: [{ label: '正常', value: 1 },{ label: '停用', value: 0 },],render: ({ row }) => {return (<el-switchactive-value={1}inactive-value={0}v-model={row.status}onChange={() => updateGoodsTypeStatusApi(row.id, row.status)}></el-switch>)},},{ prop: 'operation', label: '操作', fixed: 'right', width: 280 },
]
</script>

4.3 addOrEditType.Vue


<!--* @Date: 2024-08-17 14:18:14* @LastEditors: zhong* @LastEditTime: 2024-09-30 14:57:38* @FilePath: \admin\src\views\small\type\components\addOrEditType.vue
-->
<template><el-card><template #header><div class="card-header"><span>{{ formData.id ? '修改' : '新增' }}商品分类</span></div></template><el-card><template #header><div class="card-header"><span>{{ formData.id ? '修改' : '新增' }}商品一级分类</span></div></template><div style="display: flex;align-items: center;"><div style="flex: 1;"><el-form ref="typeFormRef" :model="formData" :rules="rules" label-width="120px" style="max-width: 660px"status-icon><el-form-item label="分类名称" prop="name"><el-input v-model="formData.name" /></el-form-item><el-form-item label="分类简介" prop="description"><el-input type="textarea" v-model="formData.description" /></el-form-item><el-form-item label="分类排序" prop="typeSort"><el-input v-model="formData.typeSort" /></el-form-item><el-form-item label="是否启用" prop="status"><el-radio-group v-model="formData.status" class="ml-4"><el-radio :label="UserStatus.DISABLED">{{getLabelByValue(UserStatusMap,UserStatus.DISABLED,)}}</el-radio><el-radio :label="UserStatus.NORMAL">{{getLabelByValue(UserStatusMap,UserStatus.NORMAL,)}}</el-radio></el-radio-group></el-form-item></el-form></div><!-- 上传操作 --><div style="width: 200px;display: flex;flex-direction: column;padding-bottom: 60px;"><text label="商品主图" /><upload-img v-model:file-list="formData.img" :on-success="uploadSuccessHandle" :on-remove="uploadRemoveHandle"list-type="picture-card" :limit="1" :class="listLengthTag === 1 ? 'hide_box' : ''"></upload-img></div></div></el-card><el-card class="m-t-20"><template #header><div class="card-header"><span>{{ formData.id ? '修改' : '新增' }}商品二级分类</span></div></template><el-row class="container"><el-col :span="2" class="text-center">二级分类</el-col><el-col :span="22" class="item-container"><el-popconfirm v-for="item in goodsTypeList || []" :key="item.id" width="220" confirm-button-text="删除"cancel-button-text="修改" cancel-button-type="warning" confirm-button-type="danger"@confirm="deleteFacilityHandle(item)" @cancel="editTypeHandle(item)" :title="`修改或直接删除${item.name}`"><template #reference><div class="item m-r-10 m-t-10 pointer"><el-image style="width: 30px; height: 30px" :src="item.img" /><span>{{ item.name }}</span></div></template></el-popconfirm><el-icon class="item m-r-10 m-t-5 pointer" :size="35" color="#567722" @click="addTypeDialog(formData)"><CirclePlus /></el-icon></el-col></el-row><!--   商品二级分类信息修改弹窗管理--><SupportTypeDialog ref="supportTypeDialog" :updateFacility="getTypeListHandle"></SupportTypeDialog></el-card><!--  --><!-- 底部保存或取消按钮 --><div class="flex-center m-t-20"><el-button style="width: 150px" type="info" @click="router.back()">取消</el-button><el-button style="width: 150px" type="primary" @click="submitHandle">{{ formData.id ? '保存' : '新增' }}</el-button></div></el-card>
</template><script setup lang="ts">
import { onMounted, ref, reactive, computed } from 'vue'
import { FacilityInfoInterface } from '@/api/apartmentManagement/types'
// import { PageResponseInterface } from '@/api/type/types'
import {deleteGoodsTypeByIdApi,getTypeSonListApi,saveOrUpdateGoodsTypeApi,} from '@/api/goodsType'import {getLabelByValue,UserStatus,UserStatusMap
} from '@/enums/constEnums'import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import UploadImg from '@/components/uploadImg/uploadImg.vue'
import SupportTypeDialog from "./supportTypeDialog.vue"
import { ElMessage, FormInstance, UploadFiles } from 'element-plus'import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()type typeFromData = {id: stringname: stringdescription: stringtypeSort: stringstatus: stringimg: any[]
}// 父类分类信息
const formData = ref<typeFromData>({id: "",name: "",description: "",typeSort: "",status: "",img: []
})const typeFormRef = ref<FormInstance>()
// 清空表单数据的函数
const clearFormData = () => {formData.value.id = "";formData.value.name = "";formData.value.description = "";formData.value.typeSort = "";formData.value.status = "";formData.value.img = [];
};
// 表单验证规则
const rules = reactive({name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],description: [{ required: true, message: '请输入分类介绍', trigger: 'blur' },],typeSort: [{ required: true, message: '请输入分类排序数值越大越靠前', trigger: 'blur' }],
})// 图片上传成功
function uploadSuccessHandle(response: any,uploadFile: UploadFile,uploadFiles: UploadFiles,) {console.log(uploadFile);formData.value.img = uploadFiles?.map((item) => {return {...item,url: (item?.response as any)?.data.url || item.url,}})console.log(formData.value.img);
}
// TODO 控制上传图片数量隐藏上传按钮
const listLengthTag = computed(() => {return formData.value.img.length;
});
// 移除图片
const uploadRemoveHandle = (uploadFiles: UploadFiles, uploadFile: UploadFile) => {console.log(uploadFiles);console.log(uploadFile);
}const supportTypeDialog = ref<any>()// 修改后刷新数据
const getTypeListHandle = () => {if (route.query?.id) {getGoodsInfoList(route.query.id as string)}
}// 子类分类信息
const goodsTypeList = ref<any>([])// 获取分类信息
async function getGoodsInfoList(id: string | number) {try {const { data } = await getTypeSonListApi(id);console.log(data);formData.value = data.fatherType?.[0];formData.value.img = [{ name: formData.value.name, url: formData.value.img }];console.log(formData.value);goodsTypeList.value = data.sonType;} catch (error) {console.log(error)}
}// 删除分类
const deleteFacilityHandle = async (item: any) => {console.log('删除分类', item)try {await deleteGoodsTypeByIdApi(item.id)await getTypeListHandle()ElMessage.success('操作成功')} catch (error) {console.log(error)}
}
// 编辑分类
const editTypeHandle = (item: typeFromData) => {console.log('编辑分类', item)supportTypeDialog.value?.show(item)
}
// 添加分类
const addTypeDialog = (item: any) => {console.log('添加分类', item)supportTypeDialog.value?.show({ type: item.id })
}// 新增或更新商品分类信息
async function addOrUpdateTypeHandle() {try {console.log(formData.value);let res = JSON.parse(JSON.stringify(formData.value));// 判断图片改变没有if (res.img?.[0]?.response) {res.img = res.img[0].response.data;} else {res.img = res.img[0].url;}await saveOrUpdateGoodsTypeApi(res);clearFormData();ElMessage.success('操作成功')router.back()} catch (error) {console.log(error)}
}
// 提交
function submitHandle() {typeFormRef.value?.validate(async (valid) => {if (valid) {await addOrUpdateTypeHandle()} else {ElMessage.error('表单填写有误,请检查')return false}})
}
onMounted(() => {if (route.query?.id) {getGoodsInfoList(route.query.id as string)}
})
</script><style scoped lang="scss">
::v-deep(.hide_box .el-upload.el-upload--picture-card) {display: none !important;
}.card-header {font-size: 18px;font-weight: bold;
}.text-center {display: flex;align-items: center;justify-content: flex-start;text-align: center;
}.container:not(:first-child) {margin-top: 20px;
}.item-container {display: flex;flex-wrap: wrap;align-items: center;justify-content: flex-start;width: 100%;padding: 10px 15px;background-color: #efefef;border-radius: 20px;.item {position: relative;display: flex;flex-direction: column;align-items: center;justify-content: center;// width: 50px;}
}
</style>

4.4 supportTypeDialog.Vue

<!--* @Date: 2024-09-29 19:45:25* @LastEditors: zhong* @LastEditTime: 2024-09-30 15:00:22* @FilePath: \admin\src\views\small\type\components\supportTypeDialog.vue
-->
<template><el-dialog v-model="dialogFormVisible" :close-on-press-escape="true" :destroy-on-close="true" :title="title"style="max-width: 700px"><div style="display: flex;align-items: center;"><div style="flex: 1;"><el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" style="max-width: 660px"status-icon><el-form-item label="分类名称" prop="name"><el-input v-model="formData.name" /></el-form-item><el-form-item label="分类简介" prop="description"><el-input type="textarea" v-model="formData.description" /></el-form-item><el-form-item label="分类排序" prop="typeSort"><el-input v-model="formData.typeSort" /></el-form-item><el-form-item label="是否上架" prop="status"><el-radio-group v-model="formData.status" class="ml-4"><el-radio :label="UserStatus.DISABLED">{{getLabelByValue(UserStatusMap,UserStatus.DISABLED,)}}</el-radio><el-radio :label="UserStatus.NORMAL">{{getLabelByValue(UserStatusMap,UserStatus.NORMAL,)}}</el-radio></el-radio-group></el-form-item></el-form></div><!-- 上传操作 --><div style="width: 200px;display: flex;flex-direction: column;padding-left: 60px;padding-bottom: 70px;"><text label="商品主图" prop="mainImage" /><upload-img v-model:file-list="formData.img" :on-success="uploadSuccessHandle" :on-remove="uploadRemoveHandle"list-type="picture-card" :limit="1" :class="listLengthTag === 1 ? 'hide_box' : ''"></upload-img></div></div><template #footer><span class="dialog-footer"><el-button @click="close">取消</el-button><el-button type="primary" @click="submitHandle">确定</el-button></span></template></el-dialog></template>
<script setup lang="ts">
import ids from 'virtual:svg-icons-names'
import { computed, ref } from 'vue'
import { FacilityInfoInterface } from '@/api/apartmentManagement/types'
import { ElMessage, FormInstance, FormRules, UploadFiles } from 'element-plus'
import { saveOrUpdateFacilityInfo } from '@/api/apartmentManagement'
import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import UploadImg from '@/components/uploadImg/uploadImg.vue'
import {getLabelByValue,UserStatus,UserStatusMap
} from '@/enums/constEnums'
import {saveOrUpdateGoodsTypeApi,
} from '@/api/goodsType'
const props = defineProps({updateFacility: {type: Function,default: () => ({}),},
})
const defaultFormData = {id: '',description: '',name: '',status: "",fatherId: "",typeSort: "",img: [],
}const formRef = ref<FormInstance>()const dialogFormVisible = ref(false)
const formData = ref<any>({...defaultFormData,
})
// 清空表单数据的函数
const clearFormData = () => {formData.value.id = "";formData.value.name = "";formData.value.description = "";formData.value.typeSort = "";formData.value.status = "";formData.value.img = [];
};
// 表单验证规则
const rules = ref<FormRules>({name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],description: [{ required: true, message: '请选择分类描述', trigger: 'change' }],typeSort: [{ required: true, message: '请输入分类排序数值越大越靠前', trigger: 'change' }],
})const title = computed(() => {return ((formData.value.id ? '修改' : '新增') + formData.value.name + '二级分类详情')
})// 图片上传成功
// TODO 控制上传图片数量隐藏上传按钮
const listLengthTag = computed(() => {return formData.value.img.length;
});
function uploadSuccessHandle(response: any,uploadFile: UploadFile,uploadFiles: UploadFiles,) {console.log(uploadFile);formData.value.img = uploadFiles?.map((item) => {return {...item,url: (item?.response as any)?.data.url || item.url,}})console.log(formData.value.img);
}
// 移除图片
const uploadRemoveHandle = (uploadFiles: UploadFiles, uploadFile: UploadFile) => {console.log(uploadFiles);console.log(uploadFile);
}
const isEdit = ref(false);
// 展示方法
const show = (data: Partial<any> = defaultFormData) => {console.log('show', data)if (data.fatherId != null) {formData.value = Object.assign({}, defaultFormData, data)formData.value.img = [{ name: data.name, url: data.img }];} else {formData.value.fatherId = data.type;formData.value.status = 1;isEdit.value = true;}dialogFormVisible.value = true
}
// 关闭方法
const close = () => {dialogFormVisible.value = false
}// 提交方法
const submitHandle = () => {formRef.value?.validate(async (valid) => {if (valid) {let res = JSON.parse(JSON.stringify(formData.value));if (isEdit && res.img?.[0]?.response) {res.img = res.img[0].response.data;} else {res.img = res.img[0].url;}await saveOrUpdateGoodsTypeApi(res)clearFormData();await props.updateFacility()ElMessage.success('操作成功')close()} else {ElMessage.error('表单填写有误,请检查')return false}})
}
// 对外暴露
defineExpose({show,close,
})
</script><style scoped lang="scss">
::v-deep(.hide_box .el-upload.el-upload--picture-card) {display: none !important;
}.icon-option {display: flex;align-items: center;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/436624.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

24 Vue3之集成TailwindCSS

Tailwind CSS Tailwind CSS是一个由js编写的CSS 框架 他是基于postCss 去解析的 官网地址Tailwind CSS 中文文档 - Tailwind CSS - 只需书写 HTML 代码&#xff0c;无需书写 CSS&#xff0c;即可快速构建美观的网站。 | TailwindCSS中文文档 | TailwindCSS中文网 对于PostCSS…

使用root账号ssh登录虚拟机ubuntu

在C:\Users\Administrator\.ssh目录下的config中&#xff0c;添加ubuntu会在根目录中&#xff0c;建立一个root文件夹。在该文件夹中建一个.ssh目录。像免密登录ubuntu设置中&#xff0c;把公钥考进去。在vscode中打开文件夹中选择要打开的文件夹&#xff0c;就可以不需要在ubu…

CentOS7 离线部署docker和docker-compose环境

一、Docker 离线安装 1. 下载docker tar.gz包 下载地址&#xff1a; Index of linux/static/stable/x86_64/ 本文选择版本&#xff1a;23.0.6 2.创建docker.service文件 vi docker.service文件内容如下&#xff1a; [Unit] DescriptionDocker Application Container Engi…

【成神之路】Ambari实战-014-代码生命周期-metainfo-cardinality详解

1.Redis 集群 metainfo.xml 示例 <?xml version"1.0"?> <metainfo><schemaVersion>2.0</schemaVersion><services><service><!-- Redis 集群服务的基本信息 --><name>REDIS</name><displayName>Redi…

Redis的基础认识与在ubuntu上的安装教程

来自Redis的自我介绍 我是Redis&#xff0c;一个中间件&#xff0c;职责是把数据存储在内存上&#xff0c;因此可以作为数据库、缓存、消息队列等场景使用。由于可以把数据存储在内存上&#xff0c;因此江湖人称快枪手 1.redis的功能特性 &#xff08;1&#xff09;数据在内存…

制造企业各部门如何参与生产成本控制与管理?

​国内制造业的分量可不轻&#xff0c;从日常生活用品到高端工业设备&#xff0c;中国制造几乎涵盖了各个领域。 不过很多制造业企业在管理方面确实存在一些难题&#xff1a;成本控制不容易&#xff0c;产品质量并不稳定&#xff0c;生产周期也常常较长。 一、中国制造业生产管…

【ZYNQ 开发】填坑!双核数据采集系统LWIP TCP发送,运行一段时间不再发送且无法ping通的问题解决

问题描述 之所以说是填坑&#xff0c;是因为之前写了一篇关于这个双核数据采集系统的调试记录&#xff0c;问题的具体表现是系统会在运行一段时间后&#xff08;随机不定时&#xff0c;长了可能将近两小时&#xff0c;短则几分钟&#xff09;&#xff0c;突然间就不向电脑发送数…

《家庭无线网络覆盖项目》

家庭无线网络覆盖报项目 目录 家庭无线网络覆盖项目 家庭无线网络覆盖项目 一、项目概述 二、设备清单及报价 三、安装调试费用 四、总报价 五、服务承诺 家庭无线网络覆盖项目 客户姓名:[客户姓名] 联系方式:[电话号码] 家庭地址:[详细地址] 一、项目概述 为客户…

docker compose 容器编排

文章目录 1、docker compose简介2、下载与安装2.1、创建指定目录存储docker compose2.2、下载docker-compose并移动到上面的目录下2.3、给docker-compose文件赋予可执行权限2.4、查看docker compose的版本 3、入门案例&#xff08;使用docker compose部署redis&#xff09;3.1、…

RTE 大会报名丨AI 时代新基建:云边端架构和 AI Infra ,RTE2024 技术专场第二弹!

所有 AI Infra 都在探寻规格和性能的最佳平衡&#xff0c;如何构建高可用的云边端协同架构&#xff1f; 语音 AI 实现 human-like 的最后一步是什么&#xff1f; AI 视频的爆炸增长&#xff0c;给新一代编解码技术提出了什么新挑战&#xff1f; 当大模型进化到实时多模态&am…

算力共享系统中数据平面和控制平面

目录 算力共享系统中数据平面和控制平面 数据平面 控制平面 算力共享系统举例 控制流程和业务流程,在算力共享系统中举例说明 控制流程 业务流程 算力共享系统中数据平面和控制平面 在算力共享系统中,数据平面和控制平面是两个关键组成部分,它们各自承担着不同的角色…

3-2 AUTOSAR RTE对Runnable的作用

返回总目录->返回总目录<- 一、前言 通过RTE给runnable提供触发事件。 runnable是可以被触发的,但是需要通过RTE来实现这个触发和调用runnable通过RTE给runnable提供所需资源。 RTE将runnable需要的一些资源通过接口传输给它(Port的实现)将BSW和SWC做隔绝。 因此OS和r…

2024/10/1 408大题专训之磁盘管理

2021&#xff1a; 2019&#xff1a; 2010&#xff1a;

【C语言】动态内存管理:malloc、calloc、realloc、free

本篇介绍一下C语言中的malloc/calloc/realloc。 使用这些函数需要包含头文件<stdlib.h>。malloc/calloc/realloc申请的空间都是 堆区的。 1.malloc和free 1.1 malloc C语言提供了一个动态内存开辟的函数malloc&#xff0c;函数原型如下。 void* malloc(size_t size);…

【docker学习】Linux系统离线方式安装docker环境方法

centos7-linux安装docker(离线方式) 下载docker的安装文件 https://download.docker.com/linux/static/stable/x86_64/ 下载的是&#xff1a;docker-18.06.3-ce.tgz 这个压缩文件 将docker-18.06.3-ce.tgz文件上传到centos7-linux系统上&#xff0c;用ftp工具上传即可 解压…

移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——15.红黑树

1.红黑树的概念 红黑树&#xff0c;是一种二叉搜索树&#xff0c;但在每个结点上增加一个存储位表示结点的颜色&#xff0c;可以是Red或 Black。 通过对任何一条从根到叶子的路径上各个结点着色方式的限制&#xff0c;红黑树确保没有一条路 径会比其他路径长出俩倍&#xff0c;…

【C++】类与对象(一)

「前言」 &#x1f308;个人主页&#xff1a; 代码探秘者 &#x1f308;C语言专栏&#xff1a;C语言 &#x1f308;C专栏&#xff1a; C &#x1f308;喜欢的诗句:天行健,君子以自强不息. 目录 [一、面向过程和面向对象初步认识][Link 2] 二、类的引入 三、类的定义 四、类…

李宏毅机器学习2022-HW8-Anomaly Detection

文章目录 TaskBaselineReportQuestion2 Code Link Task 异常检测Anomaly Detection 将data经过Encoder&#xff0c;在经过Decoder&#xff0c;根据输入和输出的差距来判断异常图像。training data是100000张人脸照片&#xff0c;testing data有大约10000张跟training data相同…

值传递和引用传递

值传递和引用传递是函数参数传递的两种类型&#xff0c;一般而言&#xff0c;基本数据类型都是值传递&#xff0c;数组和对象采用引用传递减少对象复制开销&#xff0c;但也有特例。 值和引用传递本质一样 值传递是拷贝值到函数参数&#xff0c;引用传递是拷贝引用(或者对象的指…

第十三届蓝桥杯真题Java c组C.纸张尺寸(持续更新)

博客主页&#xff1a;音符犹如代码系列专栏&#xff1a;蓝桥杯关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ 【问题描述】 在 ISO 国际标准中定义了 A0 纸张的大小为 1189mm 841mm&#…