java增删改查项目

看完谷粒学院前五天的课程后,用springboot+mybatisplus+vue写了一个酒店房间管理系统

项目结构如下:

数据库结构:

 

数据库建表语句就不在给出,一张表要含有创建的时间字段和修改时间字段

ALTER TABLE room ADD `gmt_create` DATETIME NOT NULL COMMENT '创建时间';
ALTER TABLE room ADD `gmt_modified` DATETIME NOT NULL COMMENT '更新时间';

 一、新建一个springboot项目

exam2019

需要用到的项目依赖zai1

<dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!--lombok用来简化实体类:需要安装lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <!--xls-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>
        <!--commons-io-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!--gson-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <version>2.7.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

 整合了mybatisplus直接在test里面用代码生成器将项目结构生成出来

CodeGenerator

public class CodeGenerator {

    @Test
    public void run() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir("C:\\Users\\86185\\Desktop\\exam2019" + "/src/main/java");

        gc.setAuthor("czy");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖

        //UserServie
        gc.setServiceName("%sService");	//去掉Service接口的首字母I

        gc.setIdType(IdType.AUTO); //主键策略
        //gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/exam2019?serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("roomservice"); //模块名
        //包  com.atguigu.eduservice
        pc.setParent("com.czy");
        //包  com.atguigu.eduservice.controller
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();

        strategy.setInclude("roominfo");

        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);


        // 6、执行
        mpg.execute();
    }
}

检查生成的项目结构,补全主启动类

实体类entity

Room

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="Roominfo对象", description="客房表")
public class Room implements Serializable {

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "客房编号")
    @TableField("roomNo")
    private String roomNo;

    @ApiModelProperty(value = "客房类型")
    @TableField("roomType")
    private String roomType;

    @ApiModelProperty(value = "楼层")
    @TableField("floorNo")
    private Integer floorNo;

    @ApiModelProperty(value = "房间的床位数目")
    @TableField("bedNumber")
    private Integer bedNumber;

    @ApiModelProperty(value = "房间的状态")
    private String state;

    @ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
    private Integer isDeleted;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;
}

后端接口有一个模糊查功能,这个最好拆分出来一个类来封装条件

RoomQuery

@Data
public class RoomQuery {

    @ApiModelProperty(value = "房间的床位数目")
    @TableField("bedNumber")
    private Integer bedNumber;

    @ApiModelProperty(value = "房间的状态")
    private String state;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;
}

 实体类和分拆的条件类gmtCreate、gmtModified使用了MybatisPlus的字段自动填充注解,所以需要编写一个字段填写配置类

 

 MyMetaObjectHandler 

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        //参数1:对应类中的属性名称
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
}

后面的分页需要用到Mybatisplus的分页插件

EduConfig
@Configuration
@MapperScan("com.czy.roomservice.mapper")
public class EduConfig {

    /**
     * 逻辑删除插件
     * @return
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

统一返回数据格式

项目中我们会将响应封装成json返回,最好将所有接口的数据格式统一,是前端对数据的操作更一致,一般情况下,统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态一级要返回的具体数据就可以、单数一般会包含状态码,返回消息,数据这几部分内容

 

 ResultCode 

public interface ResultCode {

    public static Integer SUCCESS = 20000; //操作成功

    public static Integer ERROR = 20001; //操作失败
}

 R

/**
 * 1.
 * 2.
 * 3.统一返回结果的类
 **/
@Data
public class R {
    @ApiModelProperty("是否成功")
    private boolean success;

    @ApiModelProperty("返回码")
    private Integer code;

    @ApiModelProperty("返回信息")
    private String message;

    @ApiModelProperty("返回数据")
    private Map<String, Object> data = new HashMap<String, Object>();

    //无参构造方法私有
    private R() {
    }

    //成功 静态方法
    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功。。。");
        return r;
    }

    //失败 静态方法
    public static R error(){
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R data(String key,Object value){
        this.data.put(key,value);
        return this;
    }

    public R data(Map<String,Object> map){
        this.setData(map);
        return this;
    }

}

 

开始编写后端接口

RoomController.java

没什么好说的,直接增删改查加模糊查的基本操作

@RestController
@RequestMapping("/room")
@CrossOrigin
public class RoomController {

    @Autowired
    private RoomService roomService;

    //1.查询所有房间
    //rest风格
    @GetMapping("findAll")
    public R findAllRoom(){
        //调用service的方法实现查询所有的操作
        List<Room> list = roomService.list(null);
        return R.ok().data("items", list);
    }

    //物理删除
    @DeleteMapping("delete/{roomNo}")
    public R deleteRoom(@PathVariable String roomNo){
        boolean flag = roomService.deleteById(roomNo);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }
    //逻辑删除
    @DeleteMapping("{id}")
    public R deleteRoomById(@PathVariable int id){
        boolean falg = roomService.removeById(id);
        if (falg){
            return R.ok();
        }else {
            return R.error();
        }
    }


    //分页查询讲师的方法
    //current 当前页
    //limit 每页记录数
    @ApiOperation(value = "分页讲师列表")
    @GetMapping("/pageRoom/{current}/{limit}")
    public R pageListTeacher(@ApiParam(name = "current", value = "当前页码") @PathVariable long current,
                             @ApiParam(name = "limit", value = "每页记录数") @PathVariable long limit) {
        //创建page对象
        Page<Room> pageTeacher = new Page<>(current, limit);
        //调用方法实现分页
        //调用方法的时候,底层封装,把分页所有的数据封装到pageTeacher对象里面

        roomService.page(pageTeacher, null);

        long total = pageTeacher.getTotal();//总记录数
        List<Room> records = pageTeacher.getRecords();//数据list集合

        return R.ok().data("total", total).data("rows", records);
    }

    //条件查询带分页的方法
    @ApiOperation(value = "条件查询分页")
    @PostMapping("pageRoomCondition/{current}/{limit}")
    public R pageRoomCondition(@ApiParam(name = "current", value = "当前页码") @PathVariable long current,
                                  @ApiParam(name = "limit", value = "每页记录数") @PathVariable long limit,
                                  @RequestBody(required = false) RoomQuery roomQuery) {

        //创建page对象
        Page<Room> pageRoom = new Page<>(current, limit);
        //构造条件
        QueryWrapper<Room> wrapper = new QueryWrapper<>();
        //多条件组合查询
        // mybatis学过  动态SQL
        String state = roomQuery.getState();
        Integer bedNumber = roomQuery.getBedNumber();
        Date begin = roomQuery.getGmtCreate();
        Date end = roomQuery.getGmtModified();
        //判断条件值是否为空,如果不为空拼接条件
        if (!StringUtils.isEmpty(state)) {
            //构造条件
            wrapper.like("state", state);
        }
        if (!StringUtils.isEmpty(bedNumber)) {
            wrapper.eq("bedNumber", bedNumber);
        }
        if (!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_modified", end);
        }

        //排序
        wrapper.orderByDesc("gmt_modified");

        //调用方法条件查询分页
        roomService.page(pageRoom, wrapper);
        long total = pageRoom.getTotal();//总记录数
        List<Room> records = pageRoom.getRecords();//数据list集合
        return R.ok().data("total", total).data("rows", records);
    }

    //添加房间
    @PostMapping("addRoom")
    public R addRoom(@RequestBody Room room){
        boolean save = roomService.save(room);
        if (save){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //根据房间id进行查找
    @GetMapping("getRoom/{id}")
    public R getRoom(@PathVariable int id){
        //构造条件
        /*QueryWrapper<Room> wrapper = new QueryWrapper<>();
        //判断条件值是否为空,如果不为空拼接条件
        if (!StringUtils.isEmpty(roomNo)) {
            //构造条件
            wrapper.eq("roomNo", roomNo);
        }
        Room item = roomService.getOne(wrapper);*/
        Room item = roomService.getById(id);
        System.out.println(item);
        return R.ok().data("room",item);
    }

    //修改房间
    @PostMapping("updateRoom")
    public R updateRoom( @RequestBody Room room){

        boolean falg = roomService.updateById(room);
        if (falg){
            return R.ok();
        }else {
            return R.error();
        }
    }
}

在项目依赖里引入了swagger,所以整合一下swagger测试一下

编写swagger的配置类SwaggerConfig

@Configuration//配置类
@EnableSwagger2//swagger注解
public class SwaggerConfig {
    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }


    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-课程中心API文档")
                .description("本文档描述了课程中心微服务接口定义")
                .version("1.0")
                .contact(new Contact("czy", "http://czy.com",
                        "1352486008@qq.com"))
                .build();
    }
}

 项目的application.properties

定义项目的服务接口、mysql数据库连接、配置mapper.xml地址,返回json的全局时间格式

# 服务端口
server.port=8001

# 环境设置:dev、test、prod
spring.profiles.active=dev

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/exam2019?serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
spring.datasource.username=root
spring.datasource.password=root

#配置mapper xml文件的路径
mybatis-plus.mapper-locations=classpath:com/czy/roomservice/mapper/xml/*.xml

#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

主启动类加@MapperScan注解,运行进入http://localhost:8001/swagger-ui.html测试

测试的时候注意数据库字段里面非空的字段,除了时间字段不用写,其他一定要注意

我这里在代码设生成器里面用的是ID策略是AUTO

经过测试,功能基本实现,开始前端页面编写

这里用到的工具是VScode、node、vue模板

node是14.15.0稳定版

 vue模板用的是谷粒学院后台模板第一套

下载package.json的时候,会出很多问题影响后面的npm run dev 的运行,我一共用了4个版本的node,所以遇到了乱七八糟的问题,但最后都是善良node_moudles重下,直到没错误(如果还不行,赶紧百度搜或者用老师版本的node)

 npm run dev 与 npm run serve的区别,参考下面的文章

npm run dev 和 npm run serve区别_时光成梦的博客-CSDN博客_npm run serve 和dev

首先将前端连接到后端接口

 vue模板运行后首先会进入一个登录页面,后端需要编写一个登录controller

 确认开启语法检查是否开启,如果开启则关闭

@RestController
@RequestMapping("/room/user")
@CrossOrigin
public class RoomLoginController {

    //login
    @PostMapping("login")
    public R login(){
        return R.ok().data("token","admin");
    }

    //info
    @GetMapping("info")
    public R info(){
        return R.ok().data("roles","[admin]").data("name","XXX").data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }
}

在前端api里面编写room.js处理room

import request from '@/utils/request' //引入已经封装好的axios 和 拦截器

export default {
    //1、房间列表(多条件分页查询)
    //page:当前页,limit:每页记录数,teacherQuery:条件对象
    getRoomListPage(page, limit, roomQuery) {
        return request({
            url: `/room/pageRoomCondition/${page}/${limit}`,
            method: 'post',
            //teacherQuery条件对象,如果后端使用RequestBody获取数据
            //data表示把对象转换成json对象进行传递到接口里
            data: roomQuery
        })
    },
    //删除房间
    deleteRoomId(id) {
        return request({
            url: `/room/${id}`,
            method: 'delete'
        })
    },
    //添加房间
    addRoom(room) {
        return request({
            url: `/room/addRoom`,
            method: 'post',
            data: room
        })
    },
    //根据id查询讲师
    getRoomInfo(id) {
        return request({
            url: `/room/getRoom/${id}`,
            method: 'get'
        })
    },
    //修改房间
    updateRoomInfo(room) {
        return request({
            url: `/room/updateRoom`,
            method: 'post',
            data: room
        })
    }
}

在router下重新编写room需要用的路由

{
        path: '/room',
        component: Layout,
        redirect: '/room/table',
        name: '房间管理',
        meta: { title: '房间管理', icon: 'example' },
        children: [{
                path: 'table',
                name: '房间列表',
                component: () =>
                    import ('@/views/room/list'),
                meta: { title: '房间列表', icon: 'table' }
            },
            {
                path: 'tree',
                name: '添加房间',
                component: () =>
                    import ('@/views/room/save'),
                meta: { title: '添加房间', icon: 'tree' }
            },
            {
                path: 'edit/:id',
                name: '修改房间',
                component: () =>
                    import ('@/views/room/save'),
                meta: { title: '修改房间', icon: 'tree' },
                hidden: true
            }
        ]
    },

在views文件夹下创建room文件夹,在创建list.vue和save.vue

list.vue

<template>
   <div class="app-container">

    <!--多条件查询表单-->
    <el-form
      :inline="true"
      class="demo-form-inline"
      style="margin-left: 20px; margin-top: 12px;">
 
      <el-form-item label="入住情况">
        <el-input v-model="roomQuery.state" placeholder="已入住"></el-input>
      </el-form-item>

      <el-form-item label="床数">
        <el-input v-model="roomQuery.bedNumber" placeholder="1"></el-input>
      </el-form-item>
      
      
      <el-form-item label="入住时间">
        <el-date-picker
          placeholder="选择开始时间"
          v-model="roomQuery.gmtCreate"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
          type="datetime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          placeholder="选择截止时间"
          v-model="roomQuery.gmtModified"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
          
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList()"
          >查询</el-button
        >
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>
    </el-form>
      
      <!-- 表格 -->
    <el-table
    :data="list"
    style="width: 100%"
    :row-class-name="tableRowClassName">
      <el-table-column prop="date" label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="roomNo" label="房间号" width="120"></el-table-column>
      <el-table-column prop="roomType" label="房间类型" width="120"> </el-table-column>
      <el-table-column prop="floorNo" label="楼层" width="160"> </el-table-column>
      <el-table-column prop="bedNumber" label="床数" width="150"> </el-table-column>
      <el-table-column prop="state" label="入住情况" width="120"> </el-table-column>
      <el-table-column prop="gmtModified" label="入住时间" width="160" />

      <el-table-column label="操作" width="350" align="center">
        <template slot-scope="scope">
          <router-link :to="'/room/edit/' + scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit">修改</el-button>
          </router-link>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

     

    <!--分页组件-->
    <el-pagination
      background
      :total="total"
      :current-page="page"
      :page-size="limit"
      style="padding: 30px 0; text-align: center"
      layout="total,prev, pager, next,jumper"
      @current-change="getList"
    >
    </el-pagination>
  </div>
</template>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>

<script>
//引入要调用的方法,teacher.js文件
import room from "@/api/room/room.js";

export default {
  //写核心代码位置
  data() {
    //1、定义变量和初始值
    return {
      list: null, //查询之后给接口返回的数据装的集合
      page: 1, //当前页
      limit: 4, //每页显示记录数
      roomQuery: {}, //条件封装对象
      total: 0, //总记录数
    };
  },
  created() {
    //页面渲染之前执行,调用method定义的方法
    //调用
    this.getList();
  },
  methods: {
    //调用具体的方法,调用room.js定义的方法
    //房间列表的方法
    getList(page = 1) {
      this.page = page;
      room
        .getRoomListPage(this.page, this.limit, this.roomQuery)
        .then((resp) => {
          //resp接口返回的数据
          // console.log(resp);
          this.list = resp.data.rows;
          console.log(this.list);
          this.total = resp.data.total;
          console.log(this.total);
        }) //请求成功
        .catch((err) => {
          console.log(err);
        }); //请求失败
    },
    tableRowClassName({row, rowIndex}) {
        if (rowIndex%2) {
          return 'warning-row';
        } else{
          return 'success-row';
        }
      },
    resetData(){
        //表单输入项数据清空
        this.roomQuery = {}
        //查询所有讲师列表
        this.getList()
    },
    
    //删除讲师的方法
    removeDataById(id){
        //alert(id)
      this.$confirm("此操作将永久删除该房间记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        //点击确定,执行then方法
        room.deleteRoomId(id)
            .then(response => {//删除成功
            //提示信息
            this.$message({
                type: "success",
                message: "删除成功!",
            });
            //刷新页面
            this.getList();
        });
    });
    }
  },
};
</script>

<style></style>

save.vue

<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="房间号">
        <el-input v-model="room.roomNo" />
      </el-form-item>
      
      <el-form-item label="客房类型">
        <el-input v-model="room.roomType" />
      </el-form-item>

      <el-form-item label="楼层">
        <el-input v-model="room.floorNo" />
      </el-form-item>

      <el-form-item label="房间床数">
        <el-input v-model="room.bedNumber" />
      </el-form-item>

      <el-form-item label="房间入住情况">
        <el-input v-model="room.state" />
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入要调用的方法,teacher.js文件
import roomApi from "@/api/room/room.js";

export default {
    data() {
        return {
           room:{
               roomNo:'',
               roomType:'',
               floorNo:1,
               bedNumber:1,
               state:''
           } 
        }
    },
    created() {//页面渲染之前执行
        this.init()
    },
    watch:{
      $route(to,from){//路由变化方式,路由发生变化,方法就会执行
      this.init()
      }
    },
    methods: {
      init(){
        //判断路径是否有id值
        if(this.$route.params && this.$route.params.id){
          //从路径获取id值
          const id = this.$route.params.id
          //调用根据id查询的方法
          this.getInfo(id)
        }else{//路径没有id值,做添加
        //清空表单
          this.room = {}
        }
      },
      //根据房间id查询的方法
      getInfo(id){
        roomApi.getRoomInfo(id)
        .then(response => {
          this.room = response.data.room
        })
      },
      saveOrUpdate(){
        //判断修改还是添加
        //根据是否有id
        if(!this.room.id){
          //添加
          this.saveRoom()
        }else{
          this.updateRoom()
        }
      },

      //修改房间的方法
      updateRoom(){
        roomApi.updateRoomInfo(this.room)
        .then(response => {
          //提示信息
          this.$message({
            type:'success',
            message:'修改成功!'
          });
          //回到列表页面,路由跳转
          this.$router.push({path:'/room/table'})
        })
      },

      //添加房间的方法
      saveRoom(){
        roomApi.addRoom(this.room)
        .then(resp => {//添加成功
          //提示信息
          this.$message({
            type:'success',
            message:'添加成功!'
          });
          //回到列表页面,路由跳转
          this.$router.push({path:'/room/table'})
        })
      }
    },
}
</script>

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值