前言

  • 前端:Vue
  • 后端:SpringBootMybatis
  • 数据库:MySQL
  • 工具:IDEA
  • 环境:JDK1.8Tomcat 8Maven

一、创建表,添加数据

1、创建数据库:CREATE table users (id int(20) auto_increment primary key,name VARCHAR(20) not null,age int(20) not null,sex varchar(20) not null,address varchar(30) not null);

2、插入数据:insert into users (name,age,sex,address) values("詹姆斯",36,"男","洛杉矶湖人");

3、插入三条数据后如下图:
在这里插入图片描述

二、IDEA创建SpringBoot项目

在这里插入图片描述
在这里插入图片描述

三、后端页面开发

1、SpringBoot启动类 DemoApplication.java
package cn.lemon.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("cn.lemon.demo.dao")
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}
2、在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.1.14.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.lemon</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- springboot tomcat 支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
3、SpringBoot 配置文件application.properties
## 端口
server.port=8081

##数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_users
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

##MyBatis配置
mybatis.mapper-locations=classpath*:mybatis/*.xml
mybatis.type-aliases-package=cn.lemon.demo.domain
4、创建实体类 User.java ,映射数据库表
package cn.lemon.demo.domain;

import java.io.Serializable;

/**
 * user 实体类
 */
public class User implements Serializable {

  private String address;
  private int age;
  private int id;
  private String name;
  private String sex;

  public String getAddress() {
    return address;
  }


  public void setAddress(String address) {
    this.address = address;
  }


  public int getAge() {
    return age;
  }


  public void setAge(int age) {
    this.age = age;
  }


  public int getId() {
    return id;
  }


  public void setId(int id) {
    this.id = id;
  }


  public String getName() {
    return name;
  }


  public void setName(String name) {
    this.name = name;
  }


  public String getSex() {
    return sex;
  }


  public void setSex(String sex) {
    this.sex = sex;
  }

  @Override
  public String toString() {
    return "User{" +
        "address='" + address + '\'' +
        ", age=" + age +
        ", id=" + id +
        ", name='" + name + '\'' +
        ", sex='" + sex + '\'' +
        '}';
  }
}
5、创建数据访问层 IUserDao.java 接口 ,IUserDao.xml 映射文件,对数据库表的增删改查
package cn.lemon.demo.dao;

import cn.lemon.demo.domain.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 数据库访问层,访问数据库
 */
@Mapper
public interface IUserDao {

  /**
   * 添加用户
   *
   * @param user
   * @return
   */
  int add(User user);


  /**
   * 删除用户
   *
   * @param id
   * @return
   */
  int delete(int id);


  /**
   * 查询所有用户
   *
   * @return
   */
  List<User> findAll();

  /**
   * 根据ID查询用户
   *
   * @param id
   * @return
   */
  User findById(Integer id);

  /**
   * 根据姓名查询所有用户
   *
   * @param name
   * @return
   */
  List<User> findByName(String name);

  /**
   * 查询行数
   *
   * @return
   */
  int getRowCount();

  /**
   * 分页查询所有用户
   *
   * @param startRows
   * @return
   */
  List<User> queryPage(Integer startRows);

  /**
   * 修改用户
   *
   * @param user
   * @return
   */
  int update(User user);


}
<?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="cn.lemon.demo.dao.IUserDao">

    <insert id="add" parameterType="user">
        INSERT INTO
          `user`(`name`,`age`,`sex`,`address`)
        VALUES
          (#{name},#{age},#{sex},#{address})
    </insert>

    <delete id="delete">
        delete from user where id = #{id}
    </delete>

    <select id="findAll" resultType="user">
        select * from user
    </select>

    <select id="findById" resultType="user">
        select * from user where id = #{id}
    </select>

    <select id="findByName" resultType="user">
        select * from user where name like concat(concat('%',#{name}),'%')
			order by id desc
    </select>

    <select id="getRowCount" resultType="Integer">
		select count(*) from user
	</select>

    <select id="queryPage" resultMap="result" parameterType="Integer">
		select * from user order by id desc
			limit #{startRows},5
	</select>

    <resultMap id="result" type="cn.lemon.demo.domain.User">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>
    </resultMap>

    <update id="update">
        update user
        set name=#{name},age=#{age},sex=#{sex},address=#{address}
        where user.id=#{id}
    </update>
</mapper>
6、创建业务层 IUserService.java接口以及UserServiceImpl.java实现类
package cn.lemon.demo.service;

import cn.lemon.demo.domain.User;

import java.util.List;

public interface IUserService {

  /**
   * 添加用户
   *
   * @param user
   * @return
   */
  User add(User user);


  /**
   * 删除用户
   *
   * @param id
   * @return
   */
  int delete(int id);


  /**
   * 查询所有用户
   *
   * @return
   */
  List<User> findAll();


  /**
   * 根据ID查询用户
   *
   * @param id
   * @return
   */
  User findById(Integer id);


  /**
   * 根据姓名查询所有用户
   *
   * @param name
   * @return
   */
  List<User> findByName(String name);


  /**
   * 查询行数
   *
   * @return
   */
  int getRowCount();


  /**
   * 分页查询所有用户
   *
   * @param startRows
   * @return
   */
  List<User> queryPage(Integer startRows);


  /**
   * 修改用户
   *
   * @param user
   * @return
   */
  int update(User user);


}
package cn.lemon.demo.service.impl;

import cn.lemon.demo.dao.IUserDao;
import cn.lemon.demo.domain.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

  @Resource
  private IUserDao iUserDao;

  @Override
  public User add(User user) {
    iUserDao.add(user);
    return user;
  }


  @Override
  public int delete(int id) {
    return iUserDao.delete(id);
  }


  @Override
  public List<User> findAll() {
    return iUserDao.findAll();
  }


  @Override
  public User findById(Integer id) {
    return iUserDao.findById(id);
  }


  @Override
  public List<User> findByName(String name) {
    return iUserDao.findByName(name);
  }


  @Override
  public int getRowCount() {
    return iUserDao.getRowCount();
  }


  @Override
  public List<User> queryPage(Integer startRows) {
    return iUserDao.queryPage(startRows);
  }


  @Override
  public int update(User user) {
    return iUserDao.update(user);
  }


}
7、创建控制层 WebController.java
package cn.lemon.demo.web.controller;

import cn.lemon.demo.domain.User;
import cn.lemon.demo.service.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class WebController {

  @Resource
  private UserServiceImpl userService;

  @RequestMapping(value = "/delete", method = RequestMethod.POST)
  public Integer delete(Integer id) {
    System.out.println(id);
    int result = userService.delete(id);
    return result;
  }

  @RequestMapping(value = "/update", method = RequestMethod.POST)
  @ResponseBody
  public String update(User user) {
    int result = userService.update(user);
    if (result >= 1) {
      return "修改成功";
    } else {
      return "修改失败";
    }

  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public User add(User user) {
    return userService.add(user);
  }

  @RequestMapping("/userList")
  @ResponseBody
  public List<User> userList() {
    return userService.findAll();
  }

  @RequestMapping("/findByName")
  @ResponseBody
  public List<User> findByName(String name) {
    return userService.findByName(name);
  }

  
  @RequestMapping(value="/page")
  @ResponseBody
  public List<User> page(Integer page){
    int pageNow = page == null ? 1 : page;
    int pageSize = 5;
    int startRows = pageSize*(pageNow-1);
    List<User> list = userService.queryPage(startRows);
    return list;
  }

  @RequestMapping(value="/rows")
  @ResponseBody
  public int rows(){
    return userService.getRowCount();
  }
}
8、创建日志文件 log4j.properties,这样我们就可以在控制台看到打印日志
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
#log4j.rootCategory=debug, CONSOLE, LOGFILE
log4j.rootCategory=debug, CONSOLE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
#log4j.appender.LOGFILE=org.apache.log4j.FileAppender
#log4j.appender.LOGFILE.File=d:\axis.log
#log4j.appender.LOGFILE.Append=true
#log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
9、服务层测试 UserServiceImplTest.java(Ctrl + Shift + T)
package cn.lemon.demo.service.impl;

import cn.lemon.demo.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {

  @Resource
  private UserServiceImpl userService;

  @Test
  public void add() {
    User user = new User();
    user.setName("马化腾");
    user.setAge(50);
    user.setSex("男");
    user.setAddress("深圳市腾讯");
    userService.add(user);
  }


  @Test
  public void delete() {
    userService.delete(16);
  }


  @Test
  public void findAll() {
    List<User> userList = userService.findAll();
    for (User user : userList) {
      System.out.println(user.getName() + user.getAddress());
    }
  }


  @Test
  public void findById() {
    User user = userService.findById(1);
    System.out.println(user.getName());
  }


  @Test
  public void findByName() {
    List<User> userList = userService.findByName("詹");
    for (User user : userList) {
      System.out.println(user.getAge() + user.getAddress());
    }
  }


  @Test
  public void getRowCount() {
    int i = userService.getRowCount();
    System.out.println(i);
  }


  @Test
  public void queryPage() {
    List<User> userList = userService.queryPage(1);
    for (User user : userList) {
      System.out.println(user.getName() + user.getAddress());
    }
  }


  @Test
  public void update() {
    User user = new User();
    user.setId(13);
    user.setName("科比");
    user.setAge(40);
    user.setSex("男");
    user.setAddress("洛杉矶湖人");
    userService.update(user);

    User user1 = userService.findById(13);
    System.out.println(user1.getName() + user1.getAddress());
  }
}

三、安装 Vue CLI脚手架

Vue 详细介绍请点击 Vue基础

1、简单介绍

1、Vue 就是一款MVVM模式的框架。
2、Node.js基于事件循环的异步IO框架
3、NPM是Node.js的包管理系统,开发人员可以遵循Common.js规范来编写Node.js模块,然后发布到NPM上供其他开发人员使用。目前已经是世界最大的包模块管理系统。

2、安装 Node.js

1、官网下载 https://nodejs.org/en/download/
2、安装完成后,控制台执行node -v,查看是否安装成功
3、在命令行中运行命令npm install -g vue-cli,安装完成
4、安装完成Node应该自带了NPM了,在控制台输入npm -v查看:
在这里插入图片描述

四、IDEA创建Vue项目

1、新建 Module -> Static Web -> Vue.js
在这里插入图片描述
在这里插入图片描述
2、配置运行环境
在这里插入图片描述
3、npm启动
在这里插入图片描述
4、运行 http://localhost:8080/
在这里插入图片描述
5、各文件夹代表的意思(有小红旗的为重点)在这里插入图片描述

五、前端页面开发

1、安装axios

在项目跟目录执行命令npm install --save axios
在这里插入图片描述
Axioss介绍:

  • axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

Axioss特点:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
2、安装element ui

在项目跟目录执行命令npm i element-ui -S
在这里插入图片描述
Element UI介绍:

  • Element UI一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库
3、修改ui\src\App.vue
<template>
  <div id="app">
    <el-row type="flex" justify="center">
      <el-col :xs="22" :sm="20" :md="18" :lg="18" :xl="16">
        <router-view/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
    }
  },
  methods: {
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
4、修改ui\src\mian.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入Elemnet-UI
import elementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import 'element-ui/lib/theme-chalk/display.css'

Vue.use(elementUI)

import axios from 'axios'
Vue.prototype.axios = axios

import qs from 'qs';
Vue.prototype.qs = qs;

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
5、修改ui\src\components\HelloWorld.vue
<template>
  <div>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="search"
          class="search_name"
          size="mini"
          placeholder="输入姓名查询">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="text"
          @click="onSearch()"
          class="el-icon-search">查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          class="el-icon-refresh"
          type="text"
          @click="refreshData">刷新
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          class="el-icon-circle-plus-outline"
          type="text"
          @click="dialogVisible = true">添加
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      highlight-current-row
      border
      style="width: 100%">
      <el-table-column
        label="编号">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="姓名">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>姓名: {{ scope.row.name }}</p>
            <div slot="reference" class="name-wrapper">
              <el-button type="text">{{ scope.row.name }}</el-button>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        label="年龄">
        <template slot-scope="scope">
          <span>{{ scope.row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="地址">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm" size="medium">
      <el-dialog
        title="编辑"
        :append-to-body='true'
        :visible.sync="dialogVisible"
        width="80%"
        :before-close="handleClose">
        <el-input type="hidden" v-model="ruleForm.id"/>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
        <el-input v-model="ruleForm.sex"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>

        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel()" size="medium">取 消</el-button>
            <el-button @click="addUser()" type="primary" size="medium">确 定</el-button>
          </span>
      </el-dialog>
    </el-form>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm" size="medium">
      <el-dialog
        title="编辑"
        :append-to-body='true'
        :visible.sync="dialogUpdate"
        width="80%"
        :before-close="handleClose">
        <el-input type="hidden" v-model="ruleForm.id"/>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-input v-model="ruleForm.sex"></el-input>
        </el-form-item>

        <el-form-item label="住址" prop="address">
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>

        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel()" size="medium">取 消</el-button>
            <el-button @click="updateUser()" type="primary" size="medium">确 定</el-button>
          </span>
      </el-dialog>
    </el-form>
    <br>
    <div class="pages">
      <el-pagination
        background
        :disabled = "disablePage"
        :current-page.sync="currentPage"
        small
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        ruleForm: {
          id: '',
          name: '',
          age: '',
          sex: '',
          address: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入地址', trigger: 'blur' },
            { min: 4, message: '长度大于 4 个字符', trigger: 'blur' }
          ],
        },
        tableData: [],
        search: '',
        dialogVisible: false,
        dialogUpdate: false,
        pageSize: 5,
        currentPage: 1,
        total: 0,
        disablePage: false
      }
    },
    methods: {
      handleEdit(index, row) {
        this.dialogUpdate = true;
        this.ruleForm = Object.assign({}, row); //这句是关键!!!
      },
      handleDelete(index, row) {
        console.log(index, row);
        this.$confirm('删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = this.qs.stringify({
            id: row.id,
          });
          this.axios({
            method: 'post',
            url:'/delete',
            data:postData
          }).then(response =>
          {
            this.getPages();
            this.currentPage = 1;
            this.axios.post('/page').then(response =>
            {
              this.tableData = response.data;
            }).catch(error =>
            {
              console.log(error);
            });
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            console.log(response);
          }).catch(error =>
          {
            console.log(error);
          });

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleClose(done) {
        this.$confirm('确认关闭?')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      handleCurrentChange() {
        console.log(`当前页: ${this.currentPage}`);
        let postData = this.qs.stringify({
          page: this.currentPage
        });
        this.axios({
          method: 'post',
          url:'/page',
          data:postData
        }).then(response =>
        {
          this.tableData = response.data;
        }).catch(error =>
        {
          console.log(error);
        });
      },
      cancel() {
        this.dialogUpdate = false;
        this.dialogVisible = false;
        this.emptyUserData();
      },
      emptyUserData(){
        this.ruleForm = {
          id: '',
          name: '',
          age: '',
          sex: '',
          address: ''
        }
      },
      addUser() {
        let postData = this.qs.stringify({
          name: this.ruleForm.name,
          age: this.ruleForm.age,
          sex: this.ruleForm.sex,
          address: this.ruleForm.address
        });
        this.axios({
          method: 'post',
          url:'/add',
          data:postData
        }).then(response =>
        {
          this.axios.post('/page').then(response =>
          {
            this.tableData = response.data;
            this.currentPage = 1;
            this.$message({
              type: 'success',
              message: '已添加!'
            });
          }).catch(error =>
          {
            console.log(error);
          });
          this.getPages();
          this.dialogVisible = false
          console.log(response);
        }).catch(error =>
        {
          console.log(error);
        });
      },
      updateUser() {
        let postData = this.qs.stringify({
          id: this.ruleForm.id,
          name: this.ruleForm.name,
          age: this.ruleForm.age,
          sex: this.ruleForm.sex,
          address: this.ruleForm.address
        });
        this.axios({
          method: 'post',
          url:'/update',
          data:postData
        }).then(response =>
        {
          this.handleCurrentChange();
          this.cancel();
          this.$message({
            type: 'success',
            message: '更新成功!'
          });
          console.log(response);
        }).catch(error =>
        {
          this.$message({
            type: 'success',
            message: '更新失败!'
          });
          console.log(error);
        });
      },
      onSearch() {
        let postData = this.qs.stringify({
          name: this.search
        });
        this.axios({
          method: 'post',
          url: '/findByName',
          data: postData
        }).then(response =>
        {
          this.tableData = response.data;
          this.disablePage = true;
        }).catch(error =>
        {
          console.log(error);
        });
      },
      getPages() {
        this.axios.post('/rows').then(response =>
        {
          this.total = response.data;
        }).catch(error =>
        {
          console.log(error);
        });
      },
      refreshData() {
        location.reload();
      }
    },
    created() {
      this.axios.post('/page').then(response =>
      {
        this.tableData = response.data;
      }).catch(error =>
      {
        console.log(error);
      });

      this.axios.post('/rows').then(response =>
      {
        this.total = response.data;
      }).catch(error =>
      {
        console.log(error);
      });

    },
  }
</script>
<style scoped>
  .search_name{
    width: 200px;
  }
  .pages{
    margin: 0px;
    padding: 0px;
    text-align: right;
  }
</style>
6、前后端整合

ui\config\index.js文件中配置proxyTable{}

    //前后端整合
    proxyTable: {
      '/': {
        target:'http://localhost:8081', // 你请求的第三方接口
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/': ''  // 替换target中的请求地址
        }
      }
    },
7、项目结构

在这里插入图片描述

六、项目运行显示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码下载

Logo

前往低代码交流专区

更多推荐