一、环境需求
jdk 1.8 mysql 5.7 node navicat idea 浏览器Json插件:jsonview -安装插件
1.vue
官网:https://cn.vuejs.org/v2/guide/
方式 一
方式同:https://blog.csdn.net/weixin_44953928/article/details/124458528
方式 二
2.element-ul
官网:https://element.eleme.cn/#/zh-CN
2 vue 的简单介绍
2.0 vue的快速启动设置
2.1 组件:简单介绍
组件的3部分
2.2全局布置
2.3 组件内设置和改动
style="min-height: 100vh"
//height这个标签的高度, line-height:属性用于设置多行元素的空间量,如多行文本的间距。text-align:用来设置元素中的的文本对齐方式
style="height: 60px; line-height: 60px; text-align: center"
//背景颜色
background-color="rgb(48,65,86)"
//文字颜色
text-color="#fff"
// 点击高亮
active-text-color="#ffd04b"
//鼠标手型,cursor(鼠标手型)属性
style="cursor: pointer"
//点击收缩(进行了绑定)
:collapse-transition="false"
:collapse="isCollapse"
2.3.1 style
vh就是当前屏幕可见高度的1%,也就是说,height:100vh == height:100%; 但是有个好处是当元素没有内容时候,设置height:100%该元素不会被撑开, 但是设置height:100vh,该元素会被撑开屏幕高度一致。
2.3.2背景颜色和文字颜色
background-color="rgb(48,65,86)"
text-color="#fff"
2.3.3 点击高亮
2.3.4 导航栏收缩
2.3.5 加图片
2.3.3 主页设置(搜索框、分页等等)
分页,表格添加
3.后端
3.1创建sprootboot
如果本地没有配置Maven,则采用pom里配置阿里云仓库,(这里我配置了本地的maven,所以这里忽略)
<repositories>
<repository>
<id>nexus-aliyun</id>
<name>nexus-aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
3.2 配置application.properties或者application.yaml 或者application.yml
server:
port: 9000
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
3.3 navicat创建新的数据库
3.4 做测试
- 使用控制层
3.6几大类的创建(entity、mapper)
3.6.1 创建entity(实体类)
方式一
方式二(lombok:不建议使用)
@Getter
@Setter
@EqualsAndHashCode
@ToString
@Data
@Cleanup
@Synchronized
@SneakyThrows
@NoArgsConstructor
@AllArgsConstructor
@Data
@Setter
@Getter
3.6.2 mapper (dao)接口
3.6.3 Controller 控制层测试
3.7进一步测试(增加数据和更新)
3.7.1 mapper和controller :只增加
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping
public Integer save(@RequestBody User user){
return userMapper.insert(user);
}
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
}
3.7.2 使用post测试
postman下载 https://app.getpostman.com/app/download/win64
postman测试接口
3.7.3 mapper、service、controller :(增加和更新)
mapper
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
@Update("update sys_user set username =#{username},password=#{password},nickname=#{nickname}, email=#{email},phone=#{phone},address=#{address} where id=#{id}")
int update(User user);
}
service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int save(User user) {
if (user.getId() == null) {
return userMapper.insert(user);
} else {
return userMapper.update(user);
}
}
}
controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
}
3.8 使用mybatis(增删改查的实现)
3.8.1创建在resources下的user.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiao.mapper.UserMapper">
<select id="getUserByMassage" resultType="com.xiao.entity.User">
</select>
<update id="update">
update sys_user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="nickname != null">
nickname = #{nickname},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="address != null">
address = #{address}
</if>
</set>
<where>
id = #{id}
</where>
</update>
</mapper>
3.8.2 UserController.java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
@DeleteMapping("/{id}")
public Integer delete(@PathVariable Integer id) {
return userMapper.deleteById(id);
}
}
3.8.3 UserMapper.java
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
int update(User user);
@Delete("delete from sys_user where id = #{id}")
Integer deleteById(@Param("id") Integer id);
}
3.8.4 UserService.java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int save(User user) {
if (user.getId() == null) {
return userMapper.insert(user);
} else {
return userMapper.update(user);
}
}
}
3.8.5 application.yml
#重新设置端口
server:
port: 9000
# mysql
spring:
datasource:
#MySQL配置
driverClassName: com.mysql.cj.jdbc.Driver
#serverTimezone=GMT%2b8 东八区
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: mapper
4.解决一些常见问题
4.1 跨域问题
import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
4.2 忽略某个字段,不展示给前端
@JsonIgnore
5.结合前后端结合
5.1 实现分页
5.1.0 首先解决跨域问题
5.1.1 实现分页后端
分页思路 SELECT * from sys_user limit 0,2; --第一页 – (2 -1) * 2 = 2 SELECT * from sys_user limit 2,2; --第二页 – (3-1)* 2 = 4 SELECT * from sys_user limit 4,2; --第三页 – 结论: limit第一个参数 = (pageNum - 1) * pageSize
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
int update(User user);
@Delete("delete from sys_user where id = #{id}")
Integer deleteById(@Param("id") Integer id);
@Select("select * from sys_user limit #{pageNum}, #{pageSize}")
List<User> selectPage(Integer pageNum, Integer pageSize);
@Select("select count(*) from sys_user")
Integer selectTotal();
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
@GetMapping("/")
public List<User> findAll() {
List<User> all = userMapper.findAll();
return all;
}
@DeleteMapping("/{id}")
public Integer delete(@PathVariable Integer id) {
return userMapper.deleteById(id);
}
@GetMapping("/page")
public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
pageNum = (pageNum - 1) * pageSize;
List<User> data = userMapper.selectPage( pageNum, pageSize);
Integer total = userMapper.selectTotal();
Map<String, Object> res = new HashMap<>();
res.put("data", data);
res.put("total", total);
return res;
}
}
5.1.2 实现分页前端
5.2 实现查询
5.2.1 先只实现一个查询
后端 前端
6.mybatis-plus的使用
官网:https://baomidou.com/
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
6.1 mybatis-plus分页插件的使用(contrller、entity、mapper、service都跟着改)
server:
port: 9000
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: mapper/*.xml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 添加分页插件
6.2 集成Swagger-Ui
访问地址:http://localhost:9000/swagger-ui/index.html
pop.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
SwaggerConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("标准接口")
.apiInfo(apiInfo("Spring Boot中使用Swagger2构建RESTful APIs", "1.0"))
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.qingge.springboot.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(String title, String version) {
return new ApiInfoBuilder()
.title(title)
.description("更多请关注: https://blog.csdn.net/xqnode")
.termsOfServiceUrl("https://blog.csdn.net/xqnode")
.contact(new Contact("xqnode", "https://blog.csdn.net/xqnode", "xiaqingweb@163.com"))
.version(version)
.build();
}
}
6.3 实现分页
package com.xiao.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiao.entity.User;
import com.xiao.mapper.UserMapper;
import com.xiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public boolean save(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping("/")
public List<User> findAll() {
return userService.list();
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return userService.removeById(id);
}
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String nickname,
@RequestParam(defaultValue = "") String address) {
IPage<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
if (!"".equals(nickname)) {
queryWrapper.like("nickname", nickname);
}
if (!"".equals(address)) {
queryWrapper.like("address", address);
}
return userService.page(page, queryWrapper);
}
}
7. 前端实现(封装axios)
7.1 vue安装axios 和 request.js封装
npm i axios -S
request.js封装
import axios from 'axios'
const request = axios.create({
baseURL: '/api',
timeout: 5000
})
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
return config
}, error => {
return Promise.reject(error)
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request
import axios from 'axios'
const request = axios.create({
baseURL: '/api',
timeout: 5000
})
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
return config
}, error => {
return Promise.reject(error)
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request
7.2 后端加入批量删除
UserController.java
package com.xiao.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiao.entity.User;
import com.xiao.mapper.UserMapper;
import com.xiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin("*")
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public boolean save(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping("/")
public List<User> findAll() {
return userService.list();
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return userService.removeById(id);
}
@PostMapping("/del/batch")
public boolean deleteBatch(@RequestBody List<Integer> ids) {
return userService.removeByIds(ids);
}
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String nickname,
@RequestParam(defaultValue = "") String address) {
IPage<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
if (!"".equals(nickname)) {
queryWrapper.like("nickname", nickname);
}
if (!"".equals(address)) {
queryWrapper.like("address", address);
}
return userService.page(page, queryWrapper);
}
}
7.3 前端加入批量删除
<template>
<el-container style="min-height: 100vh">
<el-aside :width="sideWidth + 'px'" style="background-color: rgb(238, 241, 246); box-shadow: 2px 0 6px rgb(0 21 41);">
<el-menu :default-openeds="['1', '3']" style="min-height: 100%; overflow-x: hidden"
background-color="rgb(48, 65, 86)"
text-color="#fff"
active-text-color="#ffd04b"
:collapse-transition="false"
:collapse="isCollapse"
>
<div style="height: 60px; line-height: 60px; text-align: center">
<img src="../assets/logo.png" alt="" style="width: 20px; position: relative; top: 5px; margin-right: 5px">
<b style="color: white" v-show="logoTextShow">后台管理系统</b>
</div>
<el-submenu index="1">
<template slot="title">
<i class="el-icon-message"></i>
<span slot="title">导航一</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="1-1">选项1</el-menu-item>
<el-menu-item index="1-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="1-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">选项4</template>
<el-menu-item index="1-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="2">
<template slot="title">
<i class="el-icon-menu"></i>
<span slot="title">导航二</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="2-1">选项1</el-menu-item>
<el-menu-item index="2-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="2-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="2-4">
<template slot="title">选项4</template>
<el-menu-item index="2-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="3">
<template slot="title">
<i class="el-icon-setting"></i>
<span slot="title">导航三</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="3-1">选项1</el-menu-item>
<el-menu-item index="3-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="3-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="3-4">
<template slot="title">选项4</template>
<el-menu-item index="3-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="font-size: 12px; border-bottom: 1px solid #ccc; line-height: 60px; display: flex">
<div style="flex: 1; font-size: 20px">
<span :class="collapseBtnClass" style="cursor: pointer" @click="collapse"></span>
</div>
<el-dropdown style="width: 70px; cursor: pointer">
<span>王小虎</span><i class="el-icon-arrow-down" style="margin-left: 5px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-header>
<el-main>
<div style="margin-bottom: 30px">
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>用户管理</el-breadcrumb-item>
</el-breadcrumb>
</div>
<!--搜索框-->
<div style="margin: 10px 0">
<el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="username"></el-input>
<el-input style="width: 200px" placeholder="请输入邮箱" suffix-icon="el-icon-message" v-model="email" class="ml-5"></el-input>
<el-input style="width: 200px" placeholder="请输入地址" suffix-icon="el-icon-position" v-model="address" class="ml-5"></el-input>
<el-button class="ml-5" type="primary" @click="load">搜索</el-button>
<el-button type="warning" @click="reset">重置</el-button>
</div>
<!-- 一些按钮 -->
<div style="margin: 10px 0">
<el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='确定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定批量删除这些数据吗?"
@confirm="delBatch"
>
<el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
<el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
<el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
</div>
<el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="id" label="ID" width="80"></el-table-column>
<el-table-column prop="username" label="用户名" width="140"></el-table-column>
<el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
<el-table-column prop="email" label="邮箱"></el-table-column>
<el-table-column prop="phone" label="电话"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column label="操作" width="300" align="center">
<template slot-scope="scope">
<el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='确定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定删除吗?"
@confirm="del(scope.row.id)"
>
<el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- 分页的效果-->
<div style="padding: 10px 0">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[5, 10, 15, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
<el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="30%" >
<el-form label-width="80px" size="small">
<el-form-item label="用户名">
<el-input v-model="form.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵称">
<el-input v-model="form.nickname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="form.email" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</div>
</el-dialog>
</el-main>
</el-container>
</el-container>
</template>
<script>
import request from "@/utils/request";
export default {
name: 'Home',
data() {
// const item = {
// date: '2016-05-02',
// name: '王小虎',
// address: '上海市普陀区金沙江路 1518 弄'
// };
return {
//tableData: Array(10).fill(item),
tableData: [],
total:0,
pageNum: 1,
pageSize: 5,
username: "",
email: "",
address: "",
form: {}, //添加表格,修改表格数据
dialogFormVisible: false, // 是否隐藏
multipleSelection: [], //批量删除
msg: "hello 青哥哥",
collapseBtnClass: 'el-icon-s-fold',
isCollapse: false,
sideWidth: 200,
logoTextShow: true,
headerBg: 'headerBg'
}
},
created() {
// 请求分页查询数据
this.load()
},
methods:{
collapse()
{ // 点击收缩按钮触发
this.isCollapse = !this.isCollapse
if (this.isCollapse) { // 收缩
this.sideWidth = 64
this.collapseBtnClass = 'el-icon-s-unfold'
this.logoTextShow = false
} else { // 展开
this.sideWidth = 200
this.collapseBtnClass = 'el-icon-s-fold'
this.logoTextShow = true
}
},
load(){
// request.get("http://localhost:9000/user/page?pageNum="+this.pageNum+"&pageSize=" +this.pageSize+ "&username=" + this.username).then(res => {
// console.log(res)
// this.tableData=res.records
// this.total=res.total
// })
request.get("/user/page",{
params:{
pageNum:this.pageNum,
pageSize:this.pageSize,
username:this.username,
email: this.email,
address:this.address,
}
}).then(res => {
console.log(res)
this.tableData=res.records
this.total=res.total
})
// fetch("http://localhost:9000/user/page?pageNum="+this.pageNum+"&pageSize=" +
// this.pageSize+ "&username=" + this.username).then(res => res.json()).then(res => {
// console.log(res)
// this.tableData=res.data
// this.total=res.total
// })
},
//更新页数和总数
handleSizeChange(pageSize) {
console.log(pageSize)
this.pageSize = pageSize
this.load()
},
handleCurrentChange(pageNum) {
console.log(pageNum)
this.pageNum = pageNum
this.load()
},
//更新
save() {
request.post("/user", this.form).then(res => {
if (res) {
this.$message.success("保存成功")
this.dialogFormVisible = false
this.load()
} else {
this.$message.error("保存失败")
}
})
},
handleAdd() {
this.dialogFormVisible = true
this.form = {}
},
handleEdit(row) {
this.form = row
this.dialogFormVisible = true
},
del(id) {
request.delete("/user/" + id).then(res => {
if (res) {
this.$message.success("删除成功")
this.load()
} else {
this.$message.error("删除失败")
}
})
},
handleSelectionChange(val) {
console.log(val)
this.multipleSelection = val
},
//批量删除
delBatch() {
let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]
request.post("/user/del/batch", ids).then(res => {
if (res) {
this.$message.success("批量删除成功")
this.load()
} else {
this.$message.error("批量删除失败")
}
})
},
//归零
reset() {
this.username = ""
this.email = ""
this.address = ""
this.load()
},
},
}
</script>
<style>
.headerBg {
background: #eee!important;
}
</style>
8.Mybatis-Plus自动生成代码
Mybatis-Plus自动生成代码
|