生活不易、且行且珍惜。网站首页 程序人生
从零开始做网站9-Springboot+vue简单的增删改查功能
发布时间:2022-05-27 20:40编辑:zj 阅读:文章分类:
网站互动QQ群:170915747
今天做一个完整的增删改查功能,后端开发接口,前端写样式以及调用接口。
因为很久没写过vue了,而且3.0还是第一回接触,所以一边学习一边做,进度还是稍慢的
所有功能就是分页获取列表,根据条件查询数据,新增、修改、删除数据。
前端样式用的是elementUi 框架,https://element.eleme.cn/#/zh-CN/component/icon
效果图
列表:
搜索-下拉选择搜索:
搜索-模糊搜索:
新增:新增时更换dialog标题,并清空form表单的各项值,并对输入做相关校验
编辑:
删除:
感觉也没什么难度就不细讲了 直接留下代码吧
前端完整代码:
Vue:
<template> <div> <div class="crumbs"> <el-breadcrumb separator="/"> <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 字典管理 </el-breadcrumb-item> </el-breadcrumb> </div> <div class="container"> <div class="handle-box"> <el-select v-model="query.fkCategoryId" placeholder="所属字典" class="handle-select mr10"> <el-option v-for="category in categorys" :label="category.name" :value="category.id" :key="category.id"></el-option> <!-- <el-option key="1" label="文章类别" value="1"></el-option> <el-option key="2" label="文章标签" value="2"></el-option>--> </el-select> <el-input v-model="query.name" placeholder="名称" class="handle-input mr10"></el-input> <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button> <el-button type="info" icon="el-icon-plus" @click="handleAdd">新增</el-button> </div> <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"> <!-- <el-table-column prop="id" label="序号" width="55" align="center"></el-table-column>--> <el-table-column prop="id" type="index" label="序号" width="55" align="center"></el-table-column> <el-table-column prop="name" label="名称"></el-table-column> <el-table-column prop="type" label="所属字典"> </el-table-column> <el-table-column prop="value" label="值" width="55"></el-table-column> <el-table-column prop="sort" label="排序" width="55"></el-table-column> <el-table-column prop="createDate" label="创建时间"></el-table-column> <el-table-column prop="updateDate" label="修改时间"></el-table-column> <el-table-column prop="updateBy" label="修改人"></el-table-column> <el-table-column label="操作" width="180" align="center"> <template #default="scope"> <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑 </el-button> <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button> </template> </el-table-column> </el-table> <div class="pagination"> <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination> </div> </div> <!-- 编辑弹出框 --> <el-dialog :title="editTitle" v-model="editVisible" width="30%"> <el-form label-width="80px" ref="formRef" :model="form" :rules="rules"> <el-form-item label="所属字典" prop="fkCategoryId"> <el-select v-model="form.fkCategoryId" placeholder="请选择" class="handle-select mr10"> <!-- value加冒号回显label --> <el-option v-for="category in categorys" :label="category.name" :value="category.id" :key="category.id"></el-option> </el-select> </el-form-item> <el-form-item label="名称" prop="name"> <el-input v-model="form.name"></el-input> </el-form-item> <el-form-item label="值" prop="value"> <el-input v-model.number="form.value"></el-input> </el-form-item> <el-form-item label="排序" prop="sort"> <el-input v-model.number="form.sort"></el-input> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="editVisible = false">取 消</el-button> <el-button type="primary" @click="saveEdit">确 定</el-button> </span> </template> </el-dialog> </div> </template> <script> import { ref, reactive } from "vue"; import { ElMessage, ElMessageBox } from "element-plus"; import {deleteDictionary, getDictionaryCategoryList, getDictionaryList, saveOrUpdateDictionary} from "../../api"; export default { name: "basetable", setup() { const rules = { fkCategoryId: [ {required: true, message: "请选择所属字典", trigger: "blur"} ], name: [ {required: true, message: "请填写名称", trigger: "blur"}, { min: 1, max: 40, message: '名称长度在 1 到 40 个字符', trigger: 'blur' } ], value: [ {required: true, message: "请填写值", trigger: "blur"}, { type: 'number', message: "值必须输入数字", trigger: "blur" }, ], sort: [ {required: true, message: "请填写排序", trigger: "blur"}, { type: 'number', message: "排序必须输入数字", trigger: "blur" }, { min: 1, max: 4, message: '排序长度在 1 到 4 个字符', trigger: 'blur' } ], } const query = reactive({ fkCategoryId: "", name: "", pageIndex: 1, pageSize: 5, }); const formRef = ref(null); const categorys = ref([]) const tableData = ref([]); const pageTotal = ref(0); const editTitle = ref('新增'); // 表格编辑时弹窗和保存 const editVisible = ref(false); let form = reactive({ name: "", id: "", fkCategoryId: "", value: "", sort: "", }); //获取字典类型表 getDictionaryCategoryList(query).then((res) => { console.log(res) categorys.value = res; }); // 获取列表数据 const getData = () => { getDictionaryList(query).then((res) => { tableData.value = res.records; pageTotal.value = res.total || 0; }); }; getData(); // 查询操作 const handleSearch = () => { query.pageIndex = 1; getData(); }; // 分页导航 const handlePageChange = (val) => { query.pageIndex = val; getData(); }; //新增操作 const handleAdd = () =>{ editTitle.value = "新增"; editVisible.value = true; //每次新增清空form中的值,避免编辑数据留存在form //formRef.value.resetFields(); 此方法先编辑后新增不会重置 Object.keys(form).forEach((item) => { form[item] = ""; }); } // 删除操作 const handleDelete = (index, row) => { // 二次确认删除 ElMessageBox.confirm("确定要删除吗?", "提示", { type: "warning", }).then(() => { deleteDictionary({"id":row.id}).then((res) => { if(res.success == true){ ElMessage.success("删除成功"); getData(); //删除成功刷新列表数据 }else{ ElMessage.error("删除失败") } }); }).catch(() => {}); }; let idx = -1; //编辑按钮 const handleEdit = (index, row) => { idx = index; Object.keys(form).forEach((item) => { form[item] = row[item]; }); editTitle.value = "编辑"; editVisible.value = true; }; //保存编辑 const saveEdit = () => { // 表单校验 formRef.value.validate((valid) => { if (valid) { saveOrUpdateDictionary(form).then((res) => { if(res.success == true){ editVisible.value = false; // ElMessage.success(`修改第 ${idx + 1} 行成功`); ElMessage.success("保存成功") // Object.keys(form).forEach((item) => { // tableData.value[idx][item] = form[item]; // }); getData(); // 保存成功刷新列表数据 }else{ ElMessage.error("信息保存失败") } }); } else { return false; } }); }; return { formRef, query, tableData, pageTotal, editVisible, form, categorys, handleSearch, handlePageChange, handleDelete, handleAdd, handleEdit, saveEdit, editTitle, rules }; }, }; </script> <style scoped> .handle-box { margin-bottom: 20px; } .handle-select { width: 120px; } .handle-input { width: 300px; display: inline-block; } .table { width: 100%; font-size: 14px; } .red { color: #ff0000; } .mr10 { margin-right: 10px; } .table-td-thumb { display: block; margin: auto; width: 40px; height: 40px; } </style>
前段调用接口代码:api/index.js
import request from '../utils/request'; //查询字典列表 export const getDictionaryList = (query) => { return request({ url: '/api/dictionary/pageList', method: 'get', params: query }); }; //查询字典类型列表 export const getDictionaryCategoryList = () => { return request({ url: '/api/dictionary/getDictionaryCategoryList', method: 'get' }) } //保存或更新字典数据 export const saveOrUpdateDictionary = (param) => { return request({ url: '/api/dictionary/saveOrUpdate', method: 'post', params: param }); }; //删除字典数据 export const deleteDictionary = (param) => { return request({ url: '/api/dictionary/deleteDictionary', method: 'post', params: param }); };
后端代码:
controller:
@Autowired private SysDataDictionaryService dataDictionaryService; @RequestMapping("/pageList") public Page<SysDataDictionary> pageList(Long pageIndex, Long pageSize,SysDataDictionary sysDataDictionary) { if(pageIndex==null || pageIndex == 0){ pageIndex = 1L; } if(pageSize==null || pageSize == 0){ pageSize = 10L; } Page<SysDataDictionary> page = new Page<>(pageIndex, pageSize); return dataDictionaryService.selectByPage(page, sysDataDictionary); } @RequestMapping("/getDictionaryCategoryList") public List<SysDataDictionaryCategory> getDictionaryCategoryList(){ return dataDictionaryService.getDictionaryCategoryList(); } @RequestMapping("/saveOrUpdate") public Result saveOrUpdate(HttpServletRequest request, SysDataDictionary sysDataDictionary) { return dataDictionaryService.saveOrUpdate(request, sysDataDictionary); } @RequestMapping("/deleteDictionary") public Result deleteDictionary(Long id){ return dataDictionaryService.deleteDictionary(id); }
service:
@Service public class SysDataDictionaryService { @Autowired private SysDataDictionaryMapper sysDataDictionaryMapper; @Autowired private SysDataDictionaryCategoryMapper sysDataDictionaryCategoryMapper; /** * 字典分页 * @param * @return */ public Page<SysDataDictionary> selectByPage(Page page, SysDataDictionary dataDictionary) { List<SysDataDictionary> list = sysDataDictionaryMapper.selectByPage(page, dataDictionary); page.setRecords(list); return page; } public List<SysDataDictionaryCategory> getDictionaryCategoryList(){ List<SysDataDictionaryCategory> list = sysDataDictionaryCategoryMapper.selectAll(); return list; } /** * 新增或修改 * @param request * @param model * @return */ public Result saveOrUpdate(HttpServletRequest request, SysDataDictionary model){ Result result = new Result(); String token = request.getHeader(Constance.TOKEN); String username = JwtUtils.getUsername(token); if(Tools.isEmpty(username)){ return Result.fail("获取用户信息失败"); } if(model == null){ return Result.fail("字典信息为空"); } //通过字典类型id获取字典类型 SysDataDictionaryCategory category = sysDataDictionaryCategoryMapper.selectByPrimaryKey(model.getFkCategoryId()); if(category != null){ model.setType(category.getName()); }else{ model.setType("默认类型"); } model.setUpdateBy(username); model.setUpdateDate(new Timestamp(System.currentTimeMillis())); model.setDelFlag(Constance.DelFlag_YES); if(model.getId() == null){ model.setId(IdGenerator.getIdLong()); model.setCreateBy(username); model.setCreateDate(new Timestamp(System.currentTimeMillis())); sysDataDictionaryMapper.insert(model); } else { sysDataDictionaryMapper.updateByPrimaryKey(model); } result.setSuccess(true); result.setData(model); return result; } public Result deleteDictionary(Long id){ if(Tools.isEmpty(id)){ return Result.fail("请选择一条数据删除"); } sysDataDictionaryMapper.deleteByPrimaryKey(id); return Result.ok("删除成功"); } }
mapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.zjlovelt.mapper.SysDataDictionaryMapper" > <resultMap id="BaseResultMap" type="com.zjlovelt.entity.SysDataDictionary" > <id column="id" property="id" jdbcType="BIGINT" /> <result column="fk_category_id" property="fkCategoryId" jdbcType="BIGINT" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <result column="TYPE" property="type" jdbcType="VARCHAR" /> <result column="VALUE" property="value" jdbcType="VARCHAR" /> <result column="sort" property="sort" jdbcType="DECIMAL" /> <result column="update_by" property="updateBy" jdbcType="VARCHAR" /> <result column="update_date" property="updateDate" jdbcType="TIMESTAMP" /> <result column="create_by" property="createBy" jdbcType="VARCHAR" /> <result column="create_date" property="createDate" jdbcType="TIMESTAMP" /> <result column="remark" property="remark" jdbcType="VARCHAR" /> <result column="del_flag" property="delFlag" jdbcType="CHAR" /> </resultMap> <sql id="Base_Column_List" > id, fk_category_id, NAME, TYPE, VALUE, sort, update_by, update_date, create_by, create_date, remark, del_flag </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" > select <include refid="Base_Column_List" /> from sys_data_dictionary where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" > delete from sys_data_dictionary where id = #{id,jdbcType=BIGINT} </delete> <insert id="insert" parameterType="com.zjlovelt.entity.SysDataDictionary" > insert into sys_data_dictionary (id, fk_category_id, NAME, TYPE, VALUE, sort, update_by, update_date, create_by, create_date, remark, del_flag ) values (#{id,jdbcType=BIGINT}, #{fkCategoryId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, #{sort,jdbcType=DECIMAL}, #{updateBy,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, #{remark,jdbcType=VARCHAR}, #{delFlag,jdbcType=CHAR} ) </insert> <insert id="insertSelective" parameterType="com.zjlovelt.entity.SysDataDictionary" > insert into sys_data_dictionary <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="fkCategoryId != null" > fk_category_id, </if> <if test="name != null" > NAME, </if> <if test="type != null" > TYPE, </if> <if test="value != null" > VALUE, </if> <if test="sort != null" > sort, </if> <if test="updateBy != null" > update_by, </if> <if test="updateDate != null" > update_date, </if> <if test="createBy != null" > create_by, </if> <if test="createDate != null" > create_date, </if> <if test="remark != null" > remark, </if> <if test="delFlag != null" > del_flag, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=BIGINT}, </if> <if test="fkCategoryId != null" > #{fkCategoryId,jdbcType=BIGINT}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> <if test="type != null" > #{type,jdbcType=VARCHAR}, </if> <if test="value != null" > #{value,jdbcType=VARCHAR}, </if> <if test="sort != null" > #{sort,jdbcType=DECIMAL}, </if> <if test="updateBy != null" > #{updateBy,jdbcType=VARCHAR}, </if> <if test="updateDate != null" > #{updateDate,jdbcType=TIMESTAMP}, </if> <if test="createBy != null" > #{createBy,jdbcType=VARCHAR}, </if> <if test="createDate != null" > #{createDate,jdbcType=TIMESTAMP}, </if> <if test="remark != null" > #{remark,jdbcType=VARCHAR}, </if> <if test="delFlag != null" > #{delFlag,jdbcType=CHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zjlovelt.entity.SysDataDictionary" > update sys_data_dictionary <set > <if test="fkCategoryId != null" > fk_category_id = #{fkCategoryId,jdbcType=BIGINT}, </if> <if test="name != null" > NAME = #{name,jdbcType=VARCHAR}, </if> <if test="type != null" > TYPE = #{type,jdbcType=VARCHAR}, </if> <if test="value != null" > VALUE = #{value,jdbcType=VARCHAR}, </if> <if test="sort != null" > sort = #{sort,jdbcType=DECIMAL}, </if> <if test="updateBy != null" > update_by = #{updateBy,jdbcType=VARCHAR}, </if> <if test="updateDate != null" > update_date = #{updateDate,jdbcType=TIMESTAMP}, </if> <if test="createBy != null" > create_by = #{createBy,jdbcType=VARCHAR}, </if> <if test="createDate != null" > create_date = #{createDate,jdbcType=TIMESTAMP}, </if> <if test="remark != null" > remark = #{remark,jdbcType=VARCHAR}, </if> <if test="delFlag != null" > del_flag = #{delFlag,jdbcType=CHAR}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="com.zjlovelt.entity.SysDataDictionary" > update sys_data_dictionary set fk_category_id = #{fkCategoryId,jdbcType=BIGINT}, NAME = #{name,jdbcType=VARCHAR}, TYPE = #{type,jdbcType=VARCHAR}, VALUE = #{value,jdbcType=VARCHAR}, sort = #{sort,jdbcType=DECIMAL}, update_by = #{updateBy,jdbcType=VARCHAR}, update_date = #{updateDate,jdbcType=TIMESTAMP}, remark = #{remark,jdbcType=VARCHAR}, del_flag = #{delFlag,jdbcType=CHAR} where id = #{id,jdbcType=BIGINT} </update> <!-- 分页查询 --> <select id="selectByPage" resultMap="BaseResultMap" parameterType="com.zjlovelt.entity.SysDataDictionary"> select <include refid="Base_Column_List" /> from sys_data_dictionary <where> del_flag = '0' <if test="dataDictionary.fkCategoryId != null and dataDictionary.fkCategoryId != '' "> and fk_category_id = #{dataDictionary.fkCategoryId} </if> <if test="dataDictionary.name != null and dataDictionary.name != ''"> and name like CONCAT('%',CONCAT(#{dataDictionary.name},'%')) </if> </where> order by fk_category_id desc </select> <select id="findByCategoryId" resultMap="BaseResultMap" parameterType="java.lang.Long"> select <include refid="Base_Column_List"/> from sys_data_dictionary where del_flag != '1' and fk_category_id = #{typeId} order by sort </select> <select id="findByTypeAndValue" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from sys_data_dictionary where del_flag='0' and type=#{type} and value=#{value} </select> <select id="findByType" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from sys_data_dictionary where del_flag='0' and type=#{type} </select> <select id="findByCategoryidAndValue" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from sys_data_dictionary where del_flag='0' and fk_category_id=#{fk_category_id} and value=#{value} </select> <update id="deleteById" parameterType="java.lang.Long"> update sys_data_dictionary set del_flag = '1' where id = #{id,jdbcType=BIGINT} </update> </mapper>
简单的增删改查就好了,系统也进入了功能开发阶段。后续的进度就很快了。
#去评论一下
标签:#Springboot#Vue
版权声明:本博客的所有原创内容皆为作品作者所有
转载请注明:来自ZJBLOG 链接:www.zjhuiwan.cn


「万物皆有时,比如你我相遇」
感谢大佬打赏【请选择支付宝或微信,再选择金额】
使用微信扫描二维码完成支付
