使用springboot +mybatis-plus完成单表操作的所有CRUD【根据条件查询所有,添加,修改,删除】的功能

效果图 

先导入数据

DROP TABLE IF EXISTS `tb_zone`;
CREATE TABLE `tb_zone`  (
  `id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键',
  `gmt_create` datetime(0) NOT NULL COMMENT '创建时间',
  `gmt_modified` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  `is_deleted` int(10) NOT NULL COMMENT '逻辑删除(0:正常;1:删除)',
  `is_disable` int(11) NOT NULL COMMENT '状态(0:正常;1:禁用)',
  `zone_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '名称',
  `zone_desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '专区' ROW_FORMAT = Compact;

# 主键自增
alter table tb_zone modify id int auto_increment primary key
-- ----------------------------
-- Records of tb_zone
-- ----------------------------
INSERT INTO `tb_zone` VALUES ('1', '2022-09-02 10:00:34', '2022-09-22 13:52:11', 0, 0, '农副产品', '瓜果蔬菜 无公害 无污染');
INSERT INTO `tb_zone` VALUES ('2', '2018-07-04 10:45:07', '2022-09-02 09:18:39', 0, 0, '海鲜水产', '龙虾 螃蟹 生蚝 种类齐全');
INSERT INTO `tb_zone` VALUES ('3', '2018-07-04 10:45:07', '2022-09-02 11:13:36', 0, 0, '香甜水果', '葡梨浆果 多汁鲜物');
INSERT INTO `tb_zone` VALUES ('4', '2018-07-04 10:45:07', '2021-06-21 10:58:07', 0, 0, '有机蔬菜', '无公害 脆嫩 新鲜润胃');
INSERT INTO `tb_zone` VALUES ('5', '2018-07-04 10:45:07', '2021-06-21 10:58:07', 0, 0, '粮油专区', ' 非转基因 调和油 植物油');

 引入所需依赖

<?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.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aaa</groupId>
    <artifactId>day05</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>day05</name>
    <description>day05</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!--swagger的依赖引入-->
        <dependency>
            <groupId>io.github.jianzhichun</groupId>
            <artifactId>spring-boot-starter-swagger2</artifactId>
            <version>0.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

        <!--引入mp-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--mp代码生成器的依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</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>
            <version>2.3.29</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.17.Final</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>

配置application.properties文件

spring.mvc.locale=UTF-8
spring.mvc.encoding=UTF-8
spring.codec.charset=UTF-8
# spring.http.encoding.charset=UTF-8
#
# spring.datasource.driver-class-name是Spring Boot中用于配置数据源驱动程序类名的属性。
# 该属性用于指定数据库驱动程序的类名,以便Spring Boot能够正确加载和管理数据库连接。
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# spring.datasource.url是Spring Boot中用于配置数据源连接URL的属性。
# 该属性指定了与数据库建立连接所需的URL信息,以便Spring Boot可以正确地连接到数据库。
spring.datasource.url=jdbc:mysql://localhost:3306/goods?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
# 驼峰命名法
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

# mybatis-plus.mapper-locations是MyBatis-Plus框架中用于配置Mapper XML文件位置的属性。
# 该属性指定了Mapper XML文件所在的路径,以便MyBatis-Plus能够正确加载这些文件并与数据库进行交互。
mybatis-plus.mapper-locations=classpath:/mapper/*.xml

# mybatis-plus.configuration.log-impl是MyBatis-Plus框架中用于配置日志实现类的属性。
# 该属性指定了用于记录MyBatis-Plus日志的具体实现类。
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl


设置分页插件

package com.aaa.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: MybatisPlusConfig
 * @Description: TODO
 * @date: 2023/6/21 11:47
 * @author: zzj
 * @Version: 1.0
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一级缓存和二级缓存 遵循 mybatis的规则
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        //paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

设置swagger api接口

package com.aaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * @ClassName: SwaggerConfig
 * @Description: TODO
 * @date: 2023/6/19 13:47
 * @author: zzj
 * @Version: 1.0
 */
@Configuration
public class SwaggerConfig {
    // 加在方法上,表示把方法的返回结果交于spring容器来管理该对象
    // 里面封装了接口文档信息
    @Bean
    public Docket docket(){
        /**
         * groupName群组名,就是把相似的东西,分成一组一组,并起一个组名字....
         * 比如qq里建一个分组叫 我的大学好友,就叫一个groupname,和qq群有点区别.
         */
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName("某某地图")
                .apiInfo(getInfo())
                .select()
                // 只为com.aaa.controller 包下的类生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.aaa.controller"))
                .build();
        return docket;
    }

    private ApiInfo getInfo(){
        Contact DEFAULT_CONTACT = new Contact("zzj", "https://map.baidu.com/", "110@baidu.com");
        ApiInfo apiinfo = new ApiInfo("学生管理系统 Api文档", "学生管理系统 Api文档", "1.5",
                "localhost:8080/doc.html", DEFAULT_CONTACT, "某某软件有限公司", "http://www.baidu.com");
        return apiinfo;
    }
}

定义实体类

package com.aaa.pojo;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDateTime;

/**
 * @ClassName: Student
 * @Description: TODO
 * @date: 2023/6/19 17:26
 * @author: zzj
 * @Version: 1.0
 */
@Data
@TableName(value = "tb_zone") //如果没有添加该注解默认实体类映射对应的表名
public class Zone {
    /**
     *     AUTO(0),递增 按照数据库表的主键递增模式
     *     NONE(1),人为输入id值
     *     INPUT(2),人为输入id值
     *     ASSIGN_ID(3),默认的算法。雪花算法
     *     ASSIGN_UUID(4),按照UUID生成---字符串
     */
    @TableId(type = IdType.AUTO)
    @ApiModelProperty("学生编号")

    private Integer id;
    /*
     * @TableField(value = "name")
     * @TableField(exist = false)
     * private String name;
     * */

    @ApiModelProperty(value = "创建时间")
    @TableField(value = "gmt_create")
    // 时间类型转换成json格式的注解 @JsonFormat
    // @DateTimeFormat 前端传后端的注解
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    // @JsonFormat 后端传前端的注解
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime gmtCreate;
    @ApiModelProperty(value = "更新时间")
    @TableField(value = "gmt_modified",insertStrategy = FieldStrategy.NOT_EMPTY)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime gmtModified;
    @ApiModelProperty(value = "逻辑删除")
    @TableField(value = "is_deleted",insertStrategy = FieldStrategy.NOT_EMPTY)

    private Integer isDeleted;
    @ApiModelProperty(value = "状态")
    @TableField(value = "is_disable",insertStrategy = FieldStrategy.NOT_EMPTY)

    private Integer isDisable;
    @ApiModelProperty(value = "名称")
    @TableField(value = "zone_name",insertStrategy = FieldStrategy.NOT_EMPTY)

    private String zoneName;
    @ApiModelProperty(value = "描述")
    @TableField(value = "zone_desc",insertStrategy = FieldStrategy.NOT_EMPTY)

    private String zoneDesc;
}

设置统一的json格式状态

package com.aaa.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString

@ApiModel(value = "统一相应的json数据")
public class ResultVo {
    @ApiModelProperty("状态码")
    // 表示状态码
    private Integer coce;
    @ApiModelProperty("消息提示")
    // 消息提示
    private String msg;
    @ApiModelProperty("响应的数据内容")
    // 响应的数据内容
    private Object data;

}

 设置统一的数据格式

package com.aaa.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(value = "统一相应的StudentVo 的 json数据")
public class StudentVo {
    @ApiModelProperty("名称")
    private String zoneName;
    @ApiModelProperty("状态")
    private Integer isDisable;
}

 创建controller层的类

package com.aaa.controller;

import com.aaa.pojo.Zone;
import com.aaa.service.StudentService;
import com.aaa.vo.ResultVo;
import com.aaa.vo.StudentVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName: StudentController
 * @Description: TODO
 * @date: 2023/6/19 18:28
 * @author: zzj
 * @Version: 1.0
 */
@RestController
@RequestMapping("/student")
@Api(tags ="学生接口类")
public class StudentController {
    @Autowired
    private StudentService studentService;

    // 查询
    @RequestMapping("/select")
    @ApiOperation(value = "根据id查询学生信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType ="query",name="id",value = "学生id编号",required = true,dataType = "int")
    })
    public ResultVo list(Integer current, Integer pageSize, @RequestBody StudentVo userVo){
        IPage<Zone> page = new Page<>(current,pageSize);
        QueryWrapper<Zone> wrapper = new QueryWrapper<>();
        /**
         * if(StringUtils.hasText(userVo.getUsername())){
         *              wrapper.like("username",userVo.getUsername());
         *         }
         */
        if (StringUtils.hasText(userVo.getZoneName())){
            wrapper.like("zone_name",userVo.getZoneName());
        }
        if(userVo.getIsDisable()!=null){
            wrapper.eq("is_deleted",userVo.getIsDisable());
        }
        IPage<Zone> page1 = studentService.page(page, wrapper);
        return new ResultVo(200,"查询用户成功",page1);
    }

    // @PostMapping 用于添加时的操作
    @PostMapping("/insert")
    @ApiOperation(value = "添加学生信息")
    public ResultVo save(@ApiParam(name="zone",value = "添加学生信息") @RequestBody Zone zone){
        Integer save = studentService.savel(zone);
        return save > 0 ? new ResultVo(200,"添加成功",null) : new ResultVo(500,"添加失败",null);
    }

    // 修改
    @RequestMapping("/update")
    @ApiOperation(value = "修改学生信息")
    public ResultVo update(@ApiParam(name="zone" , value="修改学生信息") @RequestBody Zone zone){
        System.out.println("我是控制层修改"+zone);
        Integer save = studentService.update(zone);
        return save > 0 ? new ResultVo(200,"修改成功",null) : new ResultVo(500,"修改失败",null);
    }

    @RequestMapping("/updateto")
    @ApiOperation(value = "修改学生信息")
    public ResultVo updateto(Integer id,Integer isDisable){
        System.out.println("我是控制层修改,id:"+id+"isDisable:"+isDisable);
        Integer save = studentService.updateto(id,isDisable);
        return save > 0 ? new ResultVo(200,"修改成功",null) : new ResultVo(500,"修改失败",null);
    }

    // 删除
    @RequestMapping("/delete")
    @ApiOperation(value = "根据id进行删除")
    public ResultVo delete(Integer id){
        System.out.println("我是控制层删除"+id);
        Integer delete = studentService.delete(id);

        return delete > 0 ? new ResultVo(200,"删除成功",null) : new ResultVo(500,"删除失败",null);
    }
}

 创建service层接口

package com.aaa.service;

import com.aaa.pojo.Zone;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * @ClassName: StudentService
 * @Description: TODO
 * @date: 2023/6/19 18:30
 * @author: zzj
 * @Version: 1.0
 */
public interface StudentService  extends IService<Zone> {
    Zone selectId(Integer id);

    /*Integer save(Zone zone);*/

    Integer update(Zone zone);

    Integer delete(Integer id);

    Integer savel(Zone zone);


    Integer updateto(Integer id, Integer isDisable);
}

创建service的接口实现类

package com.aaa.service.Impl;

import com.aaa.dao.StudentDao;
import com.aaa.pojo.Zone;
import com.aaa.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: StudentServiceImpl
 * @Description: TODO
 * @date: 2023/6/19 18:30
 * @author: zzj
 * @Version: 1.0
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, Zone> implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    public Zone selectId(Integer id) {
        return studentDao.selectById(1);
    }

    /*@Override
    public Integer save(Zone zone) {
        return studentDao.insert(zone);
    }*/

    @Override
    public Integer update(Zone zone) {
        return studentDao.updateById(zone);
    }

    @Override
    public Integer delete(Integer id) {
        return studentDao.deleteById(id);
    }

    @Override
    public Integer savel(Zone zone) {
        return studentDao.insert(zone);
    }

    @Override
    public Integer updateto(Integer id, Integer isDisable) {
        /*Map<Integer, Object> map = new HashMap<>();
        map.put(id,id);
        map.put(isDisable,isDisable);*/
        return studentDao.updateByIdto(id,isDisable);
    }


}

创建dao层

package com.aaa.dao;

import com.aaa.pojo.Zone;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * @ClassName: StudentDao
 * @Description: TODO
 * @date: 2023/6/19 17:25
 * @author: zzj
 * @Version: 1.0
 */

/**
 *
 *
 @Mapper是MyBatis框架中的一个注解,用于标识接口或类是一个Mapper(数据访问对象)接口。
  Mapper接口定义了与数据库交互的方法,包括查询、插入、更新和删除等操作。
 *
 * 通过在Mapper接口上添加@Mapper注解,MyBatis框架可以扫描并生成该接口的实现类,实现类会根据接口定义的方法自动生成相应的SQL语句,并与数据库进行交互。
 */
@Mapper
public interface StudentDao extends BaseMapper<Zone> {


    Integer updateByIdto(Integer id, Integer isDisable);
}

在mapper中书写sql语句

<?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.aaa.dao.StudentDao">

    <update id="updateByIdto">
        update goods.tb_zone set is_disable=#{isDisable} where id = #{id}
    </update>
</mapper>

书写前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <script type="text/javascript" src="/js/vue.js"></script>
    <script type="text/javascript" src="/js/index.js"></script>
    <script type="text/javascript" src="/js/axios.min.js"></script>
    <link type="text/css" rel="stylesheet" href="/css/index.css"/>
</head>
<body>
<div id="app">
    <el-form :inline="true" :model="studentVo" class="demo-form-inline">
        <el-form-item label="姓名:">
            <el-input v-model="studentVo.zoneName" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="状态">
            <el-select v-model="studentVo.isDisable" placeholder="状态">
                <el-option label="启用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="searchUser">查询</el-button>
            <el-button type="success" @click="addEmp">添加</el-button>
        </el-form-item>
    </el-form>

    <!--        <%&#45;&#45;-->
    <!--        el-table:elementui中表格的标签-->
    <!--        :data: 绑定vue中表格的数据&#45;&#45;%>-->
    <el-dialog
            title="添加提示"
            :visible.sync="dialogVisiblel"
            width="30%"
            @close="addClose"
    >
        <!-- 添加-->
        <el-form ref="empFormRule" :model="addEmpForm" :rules="empFormRule" label-width="80px">
            <!--<el-form-item label="员工头像">
                <el-upload
                        class="avatar-uploade">
                <img v-if="headurl" :src="headurl" class="avatar"/>
                <i v-else class=" el-icon-plus avatar-uploader-icon" ></i>
                </el-upload>
            </el-form-item>-->
            <el-form-item label="专区名称" prop="zoneName">
                <el-input v-model="addEmpForm.zoneName"></el-input>
            </el-form-item>
            <el-form-item label="专区描述" prop="zoneDesc">
                <el-input v-model="addEmpForm.zoneDesc"></el-input>
            </el-form-item>


            <el-form-item label="添加时间" prop="gmtCreate">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="选择日期" v-model="addEmpForm.gmtCreate"></el-date-picker>

            </el-form-item>



            <el-form-item label="状态">
                <el-select v-model="addEmpForm.isDisable" placeholder="状态">
                    <el-option label="启用" :value="0" ></el-option>
                    <el-option label="禁用" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisiblel = false">取 消</el-button>
                <el-button type="primary" @click="confirmAddEmp">确 定</el-button>
            </span>

    </el-dialog>

    <!--编辑-->
    <el-dialog
            title="编辑员工"
            :visible.sync="editDialogVisible"
            width="30%">
        <el-form ref="form" :model="editEmpForm" label-width="80px" ref="empFormRule">
            <el-form-item label="名称">
                <el-input v-model="editEmpForm.zoneName"></el-input>
            </el-form-item>
            <el-form-item label="描述">
                <el-input v-model.number="editEmpForm.zoneDesc"></el-input>
            </el-form-item>

            <el-form-item label="出生日期">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="选择日期" v-model="editEmpForm.gmtCreate" style="width: 100%;"></el-date-picker>
            </el-form-item>

            <el-form-item label="状态">
                <el-select v-model="editEmpForm.isDisable" placeholder="状态">
                    <el-option label="启用" :value="0"></el-option>
                    <el-option label="禁用" :value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmUpdateEmp">确 定</el-button>
            </span>
    </el-dialog>
    <!-- 查询-->
    <el-table
            :data="userList"
            border
            style="width: 100%">
        <el-table-column
                prop="zoneName"
                label="名称"
                width="180">
        </el-table-column>
        <el-table-column
                prop="zoneDesc"
                label="昵称">
        </el-table-column>
        <el-table-column
                prop="gmtCreate"
                label="添加时间">
        </el-table-column>
        <el-table-column
                prop="isDisable"
                label="状态">
            <template slot-scope="scope">
                <el-switch
                        style="display: block"
                        v-model="scope.row.isDisable"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="0"
                        :inactive-value="1"
                        active-text="启用"
                        inactive-text="禁用"
                        @change="changeStatus(scope.row.id,scope.row.isDisable)"
                >
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column
                label="操作">
            <template slot-scope="scope">

                <!--<el-button  type="primary" icon="el-icon-setting" size="small" @click="editEmp(scope.row)">编辑</el-button>-->
                <el-button type="danger" @click="deleteEmp(scope.row.id)">删除</el-button>

                <el-button type="primary" @click="editEmp(scope.row)">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[2,3,5,10]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>


</div>
</body>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            //是否权限
            checkAll: false,
            //被选中的复选框
            checkedCities: [],
            //所有的复选框
            cities: [],
            isIndeterminate: true,
            //接受所有用户信息
            userList:[],
            // 添加员工的表单对象
            addEmpForm:{},
            depts:[],

            // 控制编辑对话框显示和隐藏
            editDialogVisible: false,

            empFormRule:{},

            addClose:{},

            // 编辑
            editEmpForm:{},
            //条件对象
            studentVo:{},
            current:1,
            pageSize:3,
            total:0,
            // 分配权限
            dialogVisible:false,
            // 添加
            dialogVisiblel:false,
            //被分配角色的用户id
            userId:undefined,
        },
        created(){
            this.initUserTable();
        },
        methods:{
            handleCheckAllChange(val) {
                this.checkedCities = val ? this.cities : [];
                this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.cities.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
            },
            

            confirmFen(){
                //被选中的角色id  当前用户的id
                axios.get("/system/user-role/confirml?userId="+this.userId+"&roleIds="+this.checkedCities).then(result=>{
                    this.dialogVisible=false;
                    this.$message.success("分配成功");
                })
            },

            fenRole(userId){
                this.userId=userId;
                //1.显示弹出层
                this.dialogVisible=true;
                axios.get("/system/role/fenRole?userId="+userId).then(result=>{
                    this.cities=result.data.data.list;
                    this.checkedCities=result.data.data.roleIds;
                })

            },
            // isDisable
            changeStatus(id,isDisable){
                /*alert("id是"+id);
                alert("isDisable是"+isDisable);*/
                var that = this;
                /*alert(that);*/
                axios.post("/student/updateto?id="+id+"&isDisable="+isDisable,this.editEmpForm).then(function(result){

                    that.$message.success(result.data.msg);
                    // 关闭弹窗
                    that.editDialogVisible=false;
                    // 重新加载表格数据
                    that.initUserTable();
                })
            },

            // 添加
            confirmAddEmp(){
                this.$refs['empFormRule'].validate((valid=>{
                    if(valid){
                        var that = this;
                        console.log(this.addEmpForm)
                        axios.post("/student/insert",this.addEmpForm).then(function(result){

                                that.$message.success(result.data.msg);
                                // 关闭弹窗
                                that.dialogVisiblel=false;
                                // 重新加载表格数据
                                that.initUserTable();
                        })
                    }
                }))

            },
            // 添加按钮事件
            addEmp(){
                this.dialogVisiblel=true;
            },
            // 编辑
            // 确认修改员工信息
            confirmUpdateEmp() {
                var that = this;
                axios.post("/student/update",this.editEmpForm).then(function(result){

                        that.$message.success(result.data.msg);
                        // 关闭弹窗
                        that.editDialogVisible=false;
                        // 重新加载表格数据
                        that.initUserTable();
                })
            },
            // 编辑员工事件
            editEmp(row){

                this.editDialogVisible=true;
                // 当前行赋值给修改表单对象
                this.editEmpForm=row;
            },

            // initUserTable
            //删除事件
            deleteEmp(id){
                // alert(id)
                //提示框
                this.$confirm('确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(() => {
                    //通过axios调用我们的删除接口。
                    var that=this;
                    axios.get("/student/delete?id="+id).then(function(result){

                            that.$message.success(result.data.msg);
                            //2.重新加载表格数据
                            that.initUserTable();

                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handleSizeChange(val) {
                this.pageSize=val;
                this.initUserTable();
            },
            handleCurrentChange(val) {
                this.current=val;
                this.initUserTable();
            },
            searchUser(){
                this.current=1;
                this.initUserTable();
            },
            initUserTable(){
                axios.post("/student/select?current="+this.current+"&pageSize="+this.pageSize,this.studentVo).then(result=>{
                    this.userList=result.data.data.records;
                    this.total=result.data.data.total;
                })
            }
        }
    })
</script>
</html>

目录结构

最后呈现效果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值