本文主要是介绍Mybatis-Plus前后端分离多表联查模糊查询分页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
数据准备
数据库配置:
/*Navicat Premium Data TransferSource Server : localhost_3306Source Server Type : MySQLSource Server Version : 80100 (8.1.0)Source Host : localhost:3306Source Schema : test01Target Server Type : MySQLTarget Server Version : 80100 (8.1.0)File Encoding : 65001Date: 07/11/2023 16:23:00
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (`deptno` int NOT NULL AUTO_INCREMENT,`dname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`deptno`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES (1, '管理');
INSERT INTO `dept` VALUES (2, '人事');
INSERT INTO `dept` VALUES (3, '财务');
INSERT INTO `dept` VALUES (4, '销售');-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (`id` int NOT NULL AUTO_INCREMENT COMMENT '员工ID',`ename` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '员工姓名',`birthday` date NULL DEFAULT NULL COMMENT '出生日期',`hobby` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '爱好',`sex` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '性别',`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '住址',`deptno` int NULL DEFAULT NULL COMMENT '部部门id',`delid` int NULL DEFAULT 0 COMMENT '0正常1删除',PRIMARY KEY (`id`, `ename`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES (1, '张三', '2000-08-06', '音乐,篮球', '男', '河南省, 郑州市', 1, 0);
INSERT INTO `emp` VALUES (2, '李四', '2001-07-06', '吃饭,睡觉', '男', '河南省, 郑州市', 2, 0);
INSERT INTO `emp` VALUES (3, '王五', '2002-09-20', NULL, '男', '河南省, 郑州市', 3, 0);
INSERT INTO `emp` VALUES (4, '老六', '2002-08-16', '睡觉', '男', '河南省, 郑州市', 4, 0);
INSERT INTO `emp` VALUES (5, '老七', '2001-06-15', NULL, '男', '河南省, 郑州市', 1, 0);
INSERT INTO `emp` VALUES (6, '梨树华', '1999-07-08', '睡觉,音乐,吃饭', '男', '河南省,洛阳市,涧西区', 4, 0);
INSERT INTO `emp` VALUES (7, '林森', '2002-03-06', '睡觉,音乐', '男', '河南省,洛阳市,涧西区', 3, 0);
INSERT INTO `emp` VALUES (8, '小娜', '2002-03-01', '音乐,睡觉', '女', '河北省,秦皇岛市,海港区', 2, 0);SET FOREIGN_KEY_CHECKS = 1;
前端vue+elementui+router+axios
基于vue2 路由的版本不要太高了 < @4
main.js 文件(跨域配置,响应拦截器)
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from "axios";
// 引入全局组件
import pageCom from '@/components/PageComponent.vue'
Vue.component("myPage",pageCom)Vue.use(ElementUI);const instance = axios.create({baseURL: 'http://localhost:8080/'
})
instance.interceptors.response.use(responce => {if (responce.data.code == 500) {router.push({path: "/err404"});}return responce.data.t;
}, error => {return Promise.reject(error)
})
Vue.prototype.$axios = instanceVue.config.productionTip = falsenew Vue({router,render: h => h(App)
}).$mount('#app')
后端配置mybatis-plus+springboot
跨域
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@Configuration
public class CrossConfig {@Beanpublic CorsFilter corsFilter() {final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();final CorsConfiguration corsConfiguration = new CorsConfiguration();
// corsConfiguration.setAllowCredentials(true);corsConfiguration.addAllowedHeader("*"); // 允许所有的头corsConfiguration.addAllowedOrigin("*"); // 允许所有的请求源corsConfiguration.addAllowedMethod("*"); // 所欲的方法 get post delete putsource.registerCorsConfiguration("/**", corsConfiguration); // 所有的路径都允许跨域return new CorsFilter(source);}}
分页
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}
swagger(可用可不用,api文档)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class Swagger2 {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.web.controller")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台 APIs").description("服务:发布为daocke镜像,权限管理,用户管理,页面管理,日志 后台").termsOfServiceUrl("https://www.baidu.com") //代码的路径.contact(new Contact("hp",null,null)).version("1.0").build();}
}
application.yml(全局配置文件)
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql:///test01?serverTimezone=UTCpassword: rootusername: rootjackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8serialization:write-date-keys-as-timestamps: falsemvc:pathmatch:matching-strategy: ant_path_matchermybatis-plus:configuration:map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath:/mapper/*.xmlglobal-config:db-config:logic-not-delete-value: 1logic-delete-value: 0type-aliases-package: com.web.entity
pom.xml (项目依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.17</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.web</groupId><artifactId>web</artifactId><version>0.0.1-SNAPSHOT</version><name>web</name><description>web</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mp 自动生成--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3</version></dependency><!-- 模板--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.3</version></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.6</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version></dependency>
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
<!-- <version>3.0.0</version>-->
<!-- </dependency>--><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
代码书写
后端
创建基本架构
ResuUtil 类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResuUtil<T> {Integer code;String msg;T t;public static <T> ResuUtil<T> success (T t) {return new ResuUtil<>(200,"成功",t);}public static <T> ResuUtil<T> fail (T t) {return new ResuUtil<>(500,"失败",t);}
}
pageUtil类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageUtil {private Integer pageIndex = 1;private Integer pageSize = 3;
}
MP (mybatis-plus 官网代码快速生成)
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.fill.Column;import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MP {public static void main(String[] args) {FastAutoGenerator.create("jdbc:mysql:///test01","root","root")// 全局配置.globalConfig((scanner, builder) -> builder.author("hp").outputDir("D:\\Idea-web-vue2\\v2demo03\\web\\src\\main\\java\\"))// 包配置.packageConfig((scanner, builder) ->builder.parent("com.web").pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\Idea-web-vue2\\v2demo03\\web\\src\\main\\resources\\mapper")))// 策略配置.strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all"))).controllerBuilder().enableRestStyle().enableHyphenStyle().entityBuilder().enableLombok().addTableFills(new Column("create_time", FieldFill.INSERT)).build())/*模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker.templateEngine(new BeetlTemplateEngine()).templateEngine(new FreemarkerTemplateEngine())*/.execute();// 处理 all 情况}protected static List<String> getTables(String tables) {return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));}
}
EmpMapper
public interface EmpMapper extends BaseMapper<Emp> {Page getAllsPage(Page page, Emp emp, Dept dept);@Select("select * from emp where ename = #{ename}")Integer getListByName(String ename);@Select("update emp set delid=#{delid} where id=#{id} ")Integer upDid(Integer delid,Integer id);
}
EmpMapper.xml
<?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.web.mapper.EmpMapper"><resultMap id="result01" type="Emp" autoMapping="true"><id property="id" column="id"/><association property="dept" column="deptno" javaType="Dept" autoMapping="true"><id property="deptno" column="deptno"/></association></resultMap><select id="getAllsPage" resultMap="result01">select e.id,e.ename,e.birthday,e.hobby,e.sex,e.address,e.deptno,e.delid,d.deptno,d.dnamefrom emp e,dept d<where>e.deptno = d.deptno<if test="emp.ename != null and emp.ename != ''">and e.ename like concat ('%',#{emp.ename},'%')</if><if test="dept.deptno != null and dept.deptno != ''">and d.deptno = #{dept.deptno}</if></where>order by e.id desc</select>
</mapper>
IEmpService
public interface IEmpService extends IService<Emp> {Page getAllPage(PageUtil pageUtil, Emp emp, Dept dept);Integer getListByName(String ename);Integer upDid(Integer delid,Integer id);
}
EmpServiceImpl
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements IEmpService {@ResourceEmpMapper em;@Overridepublic Page getAllPage(PageUtil pageUtil, Emp emp, Dept dept) {Page page = new Page(pageUtil.getPageIndex(),pageUtil.getPageSize());return em.getAllsPage(page, emp, dept);}@Overridepublic Integer getListByName(String ename) {return em.getListByName(ename);}@Overridepublic Integer upDid(Integer delid, Integer id) {return em.upDid(delid, id);}
}
EmpController
@RestController
@RequestMapping("/emp")
@Api(tags = "员工信息")
public class EmpController {@ResourceIEmpService ies;@GetMapping("/page")@ApiOperation("查询员工全部信息并分页")@ApiImplicitParams(value = {@ApiImplicitParam(value = "页数页码",name = "pageUtil",paramType = "query"),@ApiImplicitParam(value = "员工姓名模糊查对象",name = "emp",paramType = "query"),@ApiImplicitParam(value = "部门名称模糊查对象",name = "dept",paramType = "query")})public ResuUtil getAllPage(PageUtil pageUtil, Emp emp, Dept dept) {System.out.println(emp);System.out.println(dept);return ResuUtil.success(ies.getAllPage(pageUtil,emp,dept));}@PostMapping("addOne")@ApiOperation("添加员工")@ApiImplicitParam(value = "员工信息",name = "emp",paramType = "body")public ResuUtil addEmp(@RequestBody Emp emp) {return ResuUtil.success(ies.saveOrUpdate(emp));}@GetMapping("/ename")@ApiOperation("判断重名")@ApiImplicitParam(value = "员工姓名",name = "ename",paramType = "query")public ResuUtil enameXX(String ename) {return ResuUtil.success(ies.getListByName(ename));}@PutMapping("/delid/{delid}/{id}")@ApiOperation("逻辑删除")public ResuUtil upDid(@PathVariable Integer delid,@PathVariable Integer id) {return ResuUtil.success(ies.upDid(delid, id));}
}
DeptController
@RestController
@RequestMapping("/dept")
@Api(tags = "部门信息")
public class DeptController {@ResourceIDeptService ids;@GetMapping()@ApiOperation("部门数据")public ResuUtil getAll() {return ResuUtil.success(ids.list());}}
前端
分页组件
<template><el-pagination@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="this.page.pageIndex":page-sizes="[3, 5, 7, 9]":page-size="this.page.pageSize"layout="total, sizes, prev, pager, next, jumper":total="this.list.total"></el-pagination>
</template><script>
export default {name: "PageComponent",props: ['page','list'],methods: {handleSizeChange(val) {this.$emit("getPage",{p:this.page.pageIndex,s:val})},handleCurrentChange(val) {this.$emit("getPage",{p:val,s:this.page.pageSize})},}
}
</script><style scoped></style>
HomeView
<template><div><el-button type="primary" size="mini" @click="add" style="float: left">新增</el-button><el-input style="width: 160px" v-model="emp.ename" placeholder="请输入员工姓名" clearable></el-input><el-select v-model="dept.deptno" placeholder="请选择员工部门" clearable><el-option v-for="i in this.deptList" :label="i.dname" :value="i.deptno"></el-option></el-select><el-button icon="el-icon-search" @click="init" circle></el-button><el-table:data="empList.records"borderstyle="width: 100%"><el-table-column type="index" :index="index" label="ID"></el-table-column><el-table-columnprop="id"label="员工编号"/><el-table-columnprop="ename"label="员工姓名"/><el-table-columnprop="birthday"label="出生日期"/><el-table-columnprop="hobby"label="爱好"/><el-table-columnprop="sex"label="性别"/><el-table-columnprop="address"label="住址"/><el-table-columnprop="dept.dname"label="部门"/><el-table-columnfixed="right"label="操作"width="100"><template slot-scope="scope"><el-switchv-model="scope.row.delid"active-color="#13ce66"inactive-color="#ff4949":active-value="0":inactive-value="1"@change="switchCh(scope.row)"></el-switch><el-button @click="edit(scope.row)" type="text" size="small" v-show="scope.row.delid === 0">修改</el-button></template></el-table-column></el-table><el-dialog :visible.sync="dialogFormVisible"><el-form :model="form" ref="form" :rules="rules"><!-- <el-form-item label="员工ID" prop="id">--><!-- <el-input v-model="form.id"/>--><!-- </el-form-item>--><el-form-item label="员工姓名" prop="ename"><el-input v-model="form.ename"/></el-form-item><el-form-item label="出生日期" prop="birthday"><el-date-pickertype="date"placeholder="选择日期"v-model="form.birthday":picker-options="pickerTime"style="width: 100%;"/></el-form-item><el-form-item label="爱好" prop="hobby"><el-checkbox-group v-model="form.hobby"><el-checkbox label="吃饭"/><el-checkbox label="睡觉"/><el-checkbox label="音乐"/><el-checkbox label="篮球"/></el-checkbox-group></el-form-item><el-form-item label="性别" prop="sex"><el-radio-group v-model="form.sex"><el-radio label="男"/><el-radio label="女"/></el-radio-group></el-form-item><el-form-item label="住址" prop="address"><el-cascaderv-model="form.address":options="options"@change="handleChange"clearable/></el-form-item><el-form-item label="部门" prop="deptno"><el-select v-model="form.deptno" placeholder="请选择部门" clearable><el-option v-for="i in this.deptList" :label="i.dname" :value="i.deptno"></el-option></el-select></el-form-item></el-form><div slot="footer" class="dialog-footer"><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="submitForm">确 定</el-button></div></el-dialog><my-page :page="pageUtil" :list="empList" @getPage="getPage"></my-page></div>
</template><script>export default {name: "HomeView",data() {return {pickerTime: {disabledDate(time) {return time.getTime() > (Date.now() - 567648000000)}},empList: [],deptList: [],dialogFormVisible: false,pageUtil: {pageIndex: 1,pageSize: 3,},emp: {},dept: {},form: {id: '',ename: '',birthday: '',hobby: [],sex: [],address: [],deptno: ''},rules: {ename: [{required: true, message: '请输入姓名', trigger: 'blur'},{min: 2, max: 8, message: '长度在 2 到 5 个字符', trigger: 'blur'}],birthday: [{required: true, message: '请输入出生日期', trigger: 'blur'},],sex: [{required: true, message: '请输入性别', trigger: 'array'},],address: [{required: true, message: '请选择住址', trigger: 'array'},],deptno: [{required: true, message: '请选择部门', trigger: 'blur'},]},options: [{value: '河北省',label: '河北省',children: [{value: '石家庄市',label: '石家庄市',children: [{value: '长安区',label: '长安区'}, {value: '桥东区',label: '桥东区'}, {value: '桥西区',label: '桥西区'}, {value: '新华区',label: '新华区'}]},{value: '唐山市',label: '唐山市',children: [{value: '路南区',label: '路南区'}, {value: '路北区',label: '路北区'}, {value: '古冶区',label: '古冶区'}, {value: '开平区',label: '开平区'}]},{value: '秦皇岛市',label: '秦皇岛市',children: [{value: '海港区',label: '海港区'}, {value: '山海关区',label: '山海关区'}, {value: '抚宁县',label: '抚宁县'}, {value: '复兴区',label: '复兴区'}]},{value: '邯郸市',label: '邯郸市',children: [{value: '广平县',label: '广平县'}, {value: '馆陶县',label: '馆陶县'}, {value: '魏县',label: '魏县'}, {value: '曲周县',label: '曲周县'}]}],},{value: '辽宁省',label: '辽宁省',children: [{value: '沈阳市',label: '沈阳市',children: [{value: '和平区',label: '和平区'}, {value: '沈河区',label: '沈河区'}, {value: '大东区',label: '大东区'}, {value: '皇姑区',label: '皇姑区'}]},{value: '大连市',label: '大连市',children: [{value: '中山区',label: '中山区'}, {value: '西岗区',label: '西岗区'}, {value: '沙河口区',label: '沙河口区'}, {value: '金州区',label: '金州区'}]},{value: '抚顺市',label: '抚顺市',children: [{value: '新抚区',label: '新抚区'}, {value: '露天区',label: '露天区'}, {value: '顺城区',label: '顺城区'}, {value: '抚顺县',label: '抚顺县'}]},{value: '辽阳市',label: '辽阳市',children: [{value: '白塔区',label: '白塔区'}, {value: '文圣区',label: '文圣区'}, {value: '宏伟区',label: '宏伟区'}, {value: '辽阳县',label: '辽阳县'}]}],},{value: '河南省',label: '河南省',children: [{value: '郑州市',label: '郑州市',children: [{value: '中原区',label: '中原区'}, {value: '二七区',label: '二七区'}, {value: '金水区',label: '金水区'}, {value: '中牟县',label: '中牟县'}]},{value: '开封市',label: '开封市',children: [{value: '龙亭区',label: '龙亭区'}, {value: '顺河回族区',label: '顺河回族区'}, {value: '鼓楼区',label: '鼓楼区'}, {value: '南关区',label: '南关区'}]},{value: '洛阳市',label: '洛阳市',children: [{value: '老城区',label: '老城区'}, {value: '西工区',label: '西工区'}, {value: '涧西区',label: '涧西区'}, {value: '郊区',label: '郊区'}]},{value: '南阳市',label: '南阳市',children: [{value: '宛城区',label: '宛城区'}, {value: '南召县',label: '南召县'}, {value: '方城县',label: '方城县'}, {value: '西峡县',label: '西峡县'}]}],},],}},methods: {switchCh(r) {const a = 0;const b = 1;if(r.delid === 0) {this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.$axios.put(`/emp/delid/${b}/${r.id}`);this.$message.success("删除成功");}).catch(() => {this.$message.info("已取消删除")r.delid = 0});}this.$confirm('此操作将恢复该员工, 是否继续?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.$axios.put(`/emp/delid/${a}/${r.id}`);this.$message.success("恢复成功");}).catch(() => {this.$message.info("已取消恢复")r.delid = 1});},submitForm() {this.$refs.form.validate(async (valid) => {if (valid) {const nu = await this.$axios.get(`/emp/ename?ename=${this.form.ename}`)console.log(nu)if (nu === null) {this.form.hobby = this.form.hobby.toString()this.form.address = this.form.address.toString()await this.$axios.post('/emp/addOne', this.form);await this.init();this.$message.success("添加成功")this.dialogFormVisible = false;}if (nu === 1) {this.$message.error("重名了请更改名字")}} else {this.$message.error("请检查填完了吗")return false;}});},handleChange(value) {console.log(value);},index(i) {return this.pageUtil.pageIndex * this.pageUtil.pageSize - this.pageUtil.pageSize + 1 + i},add() {this.form.id = '';this.form.ename = '';this.form.birthday = '';this.form.hobby = [];this.form.sex = [];this.form.address = [];this.form.deptno = '';this.dialogFormVisible = true},edit(row) {console.log(row);},getPage(page) {this.pageUtil.pageIndex = page.p;this.pageUtil.pageSize = page.s;this.init();},async init() {let params = {...this.pageUtil, ...this.emp, ...this.dept}this.empList = await this.$axios.get('/emp/page', {params: params})},async getDept() {this.deptList = await this.$axios.get('/dept');}},mounted() {this.init();},created() {this.getDept();}
}
</script><style scoped>
* {margin: 0;padding: 0;
}
</style>
这篇关于Mybatis-Plus前后端分离多表联查模糊查询分页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!