Java add, delete, modify and check items

After watching the first five days of courses at Grain College, I wrote a hotel room management system with springboot+mybatisplus+vue

The project structure is as follows:

Database structure:

 

The database table creation statement is not given, a table must contain the creation time field and the modification time field

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

 1. Create a new springboot project

exam2019

The project that needs to be used depends on 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>

 Integrates mybatisplus and directly uses the code generator in the test to generate the project structure

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();
    }
}

Check the generated project structure and complete the main startup class

Entity class 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;
}

The backend interface has a fuzzy search function, it is best to split out a class to encapsulate the condition

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;
}

 Entity classes and split condition classes gmtCreate and gmtModified use MybatisPlus fields to automatically fill annotations, so you need to write a field to fill in the configuration class

 

 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);
    }
}

The following paging needs to use the paging plugin of 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();
    }
}

Unified return data format

In the project, we will encapsulate the response into json and return it. It is best to unify the data format of all interfaces, so that the operation of the data by the front end is more consistent. In general, there is no fixed format for the unified return data format, as long as the returned data can be described clearly The specific data to be returned at the status level is fine, and the singular number generally includes the status code, return message, and data.

 

 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;
    }

}

 

Start writing the backend interface

RoomController.java

There is nothing to say, the basic operation of directly adding, deleting, modifying and adding fuzzy checking

@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();
        }
    }
}

Introduced swagger in project dependencies, so integrate swagger to test

Write swagger configuration class 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",
                        "[email protected]"))
                .build();
    }
}

 project's application.properties

Define the service interface of the project, mysql database connection, configure mapper.xml address, and return the global time format of 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

Add the @MapperScan annotation to the main startup class, and run it into http://localhost:8001/swagger-ui.html for testing

When testing, pay attention to the non-empty fields in the database field. Except for the time field, you do not need to write, and you must pay attention to others

I use the ID strategy in the code generator here as AUTO

After testing, the function is basically realized, and the front-end page writing starts

The tools used here are VScode, node, and vue templates

node is 14.15.0 stable version

 The vue template uses the first set of background templates of Grain Academy

When downloading package.json, there will be many problems that will affect the operation of npm run dev later. I have shared 4 versions of node, so I encountered messy problems, but in the end, I redownloaded the kind node_moudles until there was no error ( If it still doesn’t work, quickly search on Baidu or use the teacher’s version of node)

 The difference between npm run dev and npm run serve, please refer to the following article

The difference between npm run dev and npm run serve

First connect the frontend to the backend interface

 After the vue template runs, it will first enter a login page, and the backend needs to write a login controller

 Confirm whether the grammar check is enabled, if it is enabled, turn it off

@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");
    }
}

Write room.js in the front-end API to process the 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
        })
    }
}

Rewrite the route that the room needs to use under the router

{
        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
            }
        ]
    },

Create a room folder under the views folder, create list.vue and 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>

Guess you like

Origin blog.csdn.net/weixin_46511995/article/details/124992525