赞
踩
idea工具,新建springboot项目,然后再项目中新建vue模块,具体如图
- drop table if exists d_user;
- create table d_user(
- id int auto_increment primary key comment '主键',
- user_no varchar(20) not null comment '账号',
- user_name varchar(100) not null comment '名字',
- password varchar(30) not null comment '密码',
- age int null comment '年龄',
- sex int null comment '性别,1男,2女',
- phone varchar(30) null comment '电话',
- role_id int not null comment '角色id,0超级管理员,1管理员,2用户',
- is_valid varchar(4) default 'Y' null comment '是否有效,Y有效,N无效'
- ) comment '用户表';
-
- insert into d_user(user_no,user_name,password,age,sex,phone,role_id)
- values ('sa','超级管理员','1234',99,1,'13312345678',0);
- insert into d_user(user_no,user_name,password,age,sex,phone,role_id)
- values ('admin','管理员','1234',88,1,'13412345678',1);
- insert into d_user(user_no,user_name,password,age,sex,phone,role_id)
- values ('user1','用户1','1234',18,2,'13512345678',2);

- <?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.7.14</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.shrimpking</groupId>
- <artifactId>msy-storage-app02</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>msy-storage-app02</name>
- <description>Demo project for Spring Boot</description>
- <properties>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.1</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.47</version>
- </dependency>
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-generator</artifactId>
- <version>3.4.1</version>
- </dependency>
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.30</version>
- </dependency>
- <dependency>
- <groupId>com.spring4all</groupId>
- <artifactId>spring-boot-starter-swagger</artifactId>
- <version>1.5.1.RELEASE</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- </project>

- server.port=8089
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=UTC
- spring.datasource.username=root
- spring.datasource.password=mysql123
- #默认日志
- mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- mybatis-plus.type-aliases-package=com.shrimpking.pojo
- package com.shrimpking.pojo;
-
- import com.baomidou.mybatisplus.annotation.TableName;
- import com.baomidou.mybatisplus.annotation.IdType;
- import com.baomidou.mybatisplus.annotation.TableId;
- import java.io.Serializable;
- import io.swagger.annotations.ApiModel;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.Data;
- import lombok.EqualsAndHashCode;
-
- /**
- * <p>
- * 用户表
- * </p>
- *
- * @author shrimpking
- * @since 2023-08-10
- */
- @Data
- @EqualsAndHashCode(callSuper = false)
- @TableName("d_user")
- @ApiModel(value="User对象", description="用户表")
- public class User implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @ApiModelProperty(value = "主键")
- @TableId(value = "id", type = IdType.AUTO)
- private Integer id;
-
- @ApiModelProperty(value = "账号")
- private String userNo;
-
- @ApiModelProperty(value = "名字")
- private String userName;
-
- @ApiModelProperty(value = "密码")
- private String password;
-
- @ApiModelProperty(value = "年龄")
- private Integer age;
-
- @ApiModelProperty(value = "性别,1男,2女")
- private Integer sex;
-
- @ApiModelProperty(value = "电话")
- private String phone;
-
- @ApiModelProperty(value = "角色id,0超级管理员,1管理员,2用户")
- private Integer roleId;
-
- @ApiModelProperty(value = "是否有效,Y有效,N无效")
- private String isValid;
-
-
- }

- package com.shrimpking.mapper;
-
- import com.baomidou.mybatisplus.core.conditions.Wrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.Constants;
- import com.shrimpking.pojo.User;
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Param;
-
- /**
- * <p>
- * 用户表 Mapper 接口
- * </p>
- *
- * @author shrimpking
- * @since 2023-08-10
- */
- @Mapper
- public interface UserMapper extends BaseMapper<User> {
-
- IPage pageC(IPage<User> page);
-
- IPage pageC2(IPage<User> page, @Param(Constants.WRAPPER) Wrapper wrapper);
-
- }

- <?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.shrimpking.mapper.UserMapper">
-
- <!-- 通用查询映射结果 -->
- <resultMap id="BaseResultMap" type="com.shrimpking.pojo.User">
- <id column="id" property="id" />
- <result column="user_no" property="userNo" />
- <result column="user_name" property="userName" />
- <result column="password" property="password" />
- <result column="age" property="age" />
- <result column="sex" property="sex" />
- <result column="phone" property="phone" />
- <result column="role_id" property="roleId" />
- <result column="is_valid" property="isValid" />
- </resultMap>
-
- <!-- 通用查询结果列 -->
- <sql id="Base_Column_List">
- id, user_no, user_name, password, age, sex, phone, role_id, is_valid
- </sql>
-
- <select id="pageC" resultType="user">
- select * from d_user
- </select>
-
- <select id="pageC2" resultType="user">
- select * from d_user ${ew.customSqlSegment}
- </select>
- </mapper>

- package com.shrimpking.service;
-
- import com.baomidou.mybatisplus.core.conditions.Wrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.shrimpking.pojo.User;
- import com.baomidou.mybatisplus.extension.service.IService;
-
- /**
- * <p>
- * 用户表 服务类
- * </p>
- *
- * @author shrimpking
- * @since 2023-08-10
- */
- public interface UserService extends IService<User> {
-
- IPage pageC(IPage<User> page);
-
- IPage pageC2(IPage<User> page, Wrapper wrapper);
- }

- package com.shrimpking.service.impl;
-
- import com.baomidou.mybatisplus.core.conditions.Wrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.shrimpking.pojo.User;
- import com.shrimpking.mapper.UserMapper;
- import com.shrimpking.service.UserService;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * <p>
- * 用户表 服务实现类
- * </p>
- *
- * @author shrimpking
- * @since 2023-08-10
- */
- @Service
- public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
-
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public IPage pageC(IPage<User> page)
- {
- return userMapper.pageC(page);
- }
-
- @Override
- public IPage pageC2(IPage<User> page, Wrapper wrapper)
- {
- return userMapper.pageC2(page,wrapper);
-
- }
- }

- package com.shrimpking.controller;
-
-
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.core.toolkit.StringUtils;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.shrimpking.common.QueryPageParam;
- import com.shrimpking.common.Result;
- import com.shrimpking.pojo.User;
- import com.shrimpking.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.HashMap;
- import java.util.List;
-
- /**
- * <p>
- * 用户表 前端控制器
- * </p>
- *
- * @author shrimpking
- * @since 2023-08-10
- */
- @RestController
- @RequestMapping("/user")
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- //新增
- @PostMapping("/save")
- public Result save(@RequestBody User user)
- {
- return userService.save(user) ? Result.success(): Result.fail();
- }
-
- //修改
- @PostMapping("/update")
- public Result update(@RequestBody User user)
- {
- return userService.updateById(user) ? Result.success() : Result.fail();
- }
-
- //新增或修改
- @PostMapping("/saveOrUpdate")
- public boolean saveOrUpdate(@RequestBody User user){
- return userService.saveOrUpdate(user);
- }
-
- //删除
- @GetMapping("/delete")
- public Result delete(@RequestParam String id)
- {
- return userService.removeById(id) ? Result.success(): Result.fail();
- }
-
-
- //根据账号,查询唯一
- @GetMapping("/findByUserNo")
- public Result findByUserNo(@RequestParam String userNo)
- {
- System.out.println(userNo);
- List<User> list = userService.lambdaQuery().eq(User::getUserNo, userNo).list();
- return list.size() > 0 ? Result.success(list) : Result.fail();
- }
-
- //
- @GetMapping("/list")
- public List<User> list()
- {
- return userService.list();
- }
-
- //查询,模糊查询
- @PostMapping("/listP")
- public Result listP(@RequestBody User user)
- {
- LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
- if(StringUtils.isNotBlank(user.getUserName()))
- {
- lambdaQueryWrapper.like(User::getUserName,user.getUserName());
- //lambdaQueryWrapper.eq(User::getUserName,user.getUserName());
- }
- return Result.success(userService.list(lambdaQueryWrapper));
- }
-
- //入参封装
- @PostMapping("/listP2")
- public List<User> listP2(@RequestBody QueryPageParam query)
- {
- System.out.println(query);
- System.out.println("pageSize=" + query.getPageSize());
- System.out.println("pageNum = " + query.getPageNum());
- HashMap param = query.getParam();
- System.out.println(param.get("name"));
-
- return null;
- }
-
- //使用mybatis默认分页类
- @PostMapping("/listPage")
- public Result listPage(@RequestBody QueryPageParam query)
- {
- //分页类
- Page<User> page = new Page<>();
- page.setCurrent(query.getPageNum());
- page.setSize(query.getPageSize());
- //查询条件
- LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
- //System.out.println(query);
- String name = (String) query.getParam().get("name");
- String sex = (String) query.getParam().get("sex");
- if(StringUtils.isNotBlank(name) && !"null".equals(name))
- {
- wrapper.like(User::getUserName,name);
- }
- if(StringUtils.isNotBlank(sex))
- {
- wrapper.eq(User::getSex,sex);
- }
- //获取分页结果
- IPage result = userService.page(page,wrapper);
- //System.out.println(result.getTotal());
- return Result.success(result.getRecords(),result.getTotal());
- }
-
- //自定义sql的分页实现
- @PostMapping("/listPage2")
- public List listPage2(@RequestBody QueryPageParam query)
- {
- Page<User> page = new Page<>();
- page.setCurrent(query.getPageNum());
- page.setSize(query.getPageSize());
-
- IPage result = userService.pageC(page);
- return result.getRecords();
- }
-
- //自定义sql的分页实现,可以有sql条件
- @PostMapping("/listPage3")
- public List listPage3(@RequestBody QueryPageParam query)
- {
- Page<User> page = new Page<>();
- page.setCurrent(query.getPageNum());
- page.setSize(query.getPageSize());
-
- LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
- wrapper.like(User::getUserName,query.getParam().get("name"));
-
- IPage result = userService.pageC2(page,wrapper);
-
- return result.getRecords();
- }
-
-
- @PostMapping("/listPage4")
- public Result listPage4(@RequestBody QueryPageParam query)
- {
- Page<User> page = new Page<>();
- page.setCurrent(query.getPageNum());
- page.setSize(query.getPageSize());
-
- LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
- wrapper.like(User::getUserName,query.getParam().get("name"));
-
- IPage res = userService.page(page,wrapper);
- return Result.success(res.getRecords(),res.getTotal());
-
- }
-
- }

配置分页拦截器
- package com.shrimpking.config;
-
- import com.baomidou.mybatisplus.annotation.DbType;
- import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
- import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- /**
- * @author user1
- */
- @Configuration
- public class MybatisPlusConfig {
-
- /**
- * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
- */
- @Bean
- public MybatisPlusInterceptor mybatisPlusInterceptor() {
- MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
- interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
- return interceptor;
- }
- }

配置跨域问题
- package com.shrimpking.config;
-
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.CorsRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- // 案例 一
- @Configuration
- public class CorsConfig implements WebMvcConfigurer
- {
-
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**")
- //是否发送Cookie
- .allowCredentials(true)
- //放行哪些原始域
- .allowedOriginPatterns("*")
- .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
- .allowedHeaders("*")
- .exposedHeaders("*");
- }
- }

分页,入参,封装一下
- package com.shrimpking.common;
-
- import lombok.Data;
-
- import java.util.HashMap;
-
- /**
- * Created by IntelliJ IDEA.
- *
- * @Author : Shrimpking
- * @create 2023/8/10 16:28
- * 入参封装
- */
- @Data
- public class QueryPageParam
- {
- //常量
- private static int PAGE_SIZE = 20;
- private static int PAGE_NUM = 1;
-
- private Integer pageSize = PAGE_SIZE;
- private Integer pageNum = PAGE_NUM;
- private HashMap param = new HashMap();
-
- }

返回给前端数据时,包装一下,携带必要的信息
- package com.shrimpking.common;
-
- import lombok.Data;
-
- /**
- * Created by IntelliJ IDEA.
- *
- * @Author : Shrimpking
- * @create 2023/8/10 18:31
- * 封装返回结果类
- */
- @Data
- public class Result
- {
- //编码 200 400
- private Integer code;
- //成功 失败
- private String msg;
- //总记录数
- private Long total;
- //数据
- private Object data;
-
-
- /**
- * 成功时返回
- * @param data
- * @param total
- * @return
- */
- public static Result success(Object data,Long total)
- {
- return result(200,"成功",total,data);
- }
-
-
- /**
- * 成功时返回
- * @return
- */
- public static Result success()
- {
- return result(200,"成功",-1L,null);
- }
-
- /**
- * 成功时返回
- * @param data
- * @return
- */
- public static Result success(Object data)
- {
- return result(200,"成功",-1L,data);
- }
-
- /**
- * 失败时返回
- * @return
- */
- public static Result fail()
- {
- return result(400,"失败",0L,null);
- }
-
- /**
- *
- * @param code
- * @param msg
- * @param total
- * @param data
- * @return
- */
- private static Result result(Integer code,String msg,long total,Object data)
- {
- Result res = new Result();
- res.setData(data);
- res.setMsg(msg);
- res.setCode(code);
- res.setTotal(total);
- return res;
- }
-
-
- }

- import Vue from 'vue'
- import App from './App.vue'
- import ElementUI from 'element-ui';
- import 'element-ui/lib/theme-chalk/index.css';
- import '@/styles/common.css'
- import axios from "axios";
-
- Vue.prototype.$axios = axios;
- Vue.prototype.$httpUrl = 'http://localhost:8089';
-
- Vue.use(ElementUI, { size: 'small'});
- Vue.config.productionTip = false;
-
- new Vue({
- render: h => h(App),
- }).$mount('#app');

- <template>
- <div id="app">
- <index></index>
- </div>
- </template>
-
- <script>
-
- import Index from "@/components/Index";
-
- export default {
- name: 'App',
- components: {
- Index
- }
- }
- </script>
-
- <style>
-
- </style>

- *{
- padding: 0;
- margin: 0;
- }
-
- <template>
- <div style="width:100%;height: 100vh;">
- <el-container style="height: 100%; border: 1px solid #eee">
- <el-aside :width="asideWidth" style="background-color: rgb(238, 241, 246);height: 100%;margin-left: -1px;">
- <Aside :isCollapse="isCollapse"></Aside>
- </el-aside>
-
- <el-container style="width:100%;height:100%;">
- <el-header style="text-align: right; font-size: 12px;width: 100%;border-bottom: 1px solid #cccccc;">
- <Header @doCollapse="handleCollapse" :icon="icon"></Header>
- </el-header>
- <el-main>
- <Main></Main>
- </el-main>
- </el-container>
- </el-container>
- </div>
- </template>
-
- <script>
- import Aside from "@/components/Aside";
- import Header from "@/components/Header";
- import Main from "@/components/Main";
- export default {
- name: "IndexPage",
- data(){
- return {
- isCollapse: false,
- asideWidth: '200px',
- icon:'el-icon-s-fold'
- }
- },
- components:{
- Aside,
- Header,
- Main
- },
- methods:{
- //折叠左侧菜单栏
- handleCollapse(){
- this.isCollapse = !this.isCollapse;
- //折叠菜单栏时,也缩放宽度
- this.asideWidth = this.isCollapse ? '64px' : '200px';
- this.icon = this.isCollapse ? 'el-icon-s-unfold':'el-icon-s-fold';
- }
- }
- }
- </script>
-
- <style scoped>
- .el-header {
- #background-color: #B3C0D1;
- color: #333;
- line-height: 60px;
- }
-
- .el-aside {
- color: #333;
- }
- </style>

- <template>
- <div style="display: flex;line-height: 60px;">
- <div @click="collapse" style="cursor: pointer;">
- <i :class="icon" style="font-size:20px;"></i>
- </div>
- <div style="flex: 1;text-align: center;font-size: 34px;">
- <span>欢迎来到仓库管理系统</span>
- </div>
- <el-dropdown>
- <span>王小虎</span>
- <i class="el-icon-arrow-down" style="margin-right: 15px;margin-left:5px;"></i>
- <el-dropdown-menu slot="dropdown">
- <el-dropdown-item @click.native="toUser">个人中心</el-dropdown-item>
- <el-dropdown-item @click.native="logout">退出</el-dropdown-item>
- </el-dropdown-menu>
- </el-dropdown>
- </div>
- </template>
-
- <script>
- export default {
- name: "HeaderPart",
- props:{
- icon: String
- },
- methods:{
- toUser(){
- console.log('to_user');
- },
- logout(){
- console.log("logout");
- },
- //折叠左侧菜单栏
- collapse(){
- this.$emit('doCollapse');
- }
- }
- }
- </script>
-
- <style scoped>
-
- </style>

- <template>
- <el-menu
- background-color="#545c64"
- text-color="#fff"
- active-text-color="#ffd04b"
- style="height: 100%;"
- default-active="/home"
- :collapse="isCollapse"
- :collapse-transition="false">
- <el-menu-item index="/home">
- <i class="el-icon-s-home"></i>
- <span slot="title">首页</span>
- </el-menu-item>
- <el-menu-item index="/One">
- <i class="el-icon-s-flag"></i>
- <span slot="title">导航一</span>
- </el-menu-item>
- <el-menu-item index="/Two">
- <i class="el-icon-s-opportunity"></i>
- <span slot="title">导航二</span>
- </el-menu-item>
- </el-menu>
- </template>
-
- <script>
- export default {
- name: "AsidePart",
- data(){
- return {
-
- }
- },
- //折叠左侧菜单栏
- props:{
- isCollapse: Boolean
- }
- }
- </script>
-
- <style scoped>
-
- </style>

- <template>
- <div>
- <div style="margin-bottom: 10px;">
- <el-input v-model="userName"
- placeholder="请输入名字"
- style="width:300px;"
- suffix-icon="el-icon-search"
- @keyup.enter.native="loadPost"></el-input>
- <el-select v-model="sex" placeholder="请选择性别" style="margin-left:10px;width:300px;">
- <el-option
- v-for="item in sexList"
- :key="item.value"
- :label="item.label"
- :value="item.value">
- </el-option>
- </el-select>
- <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
- <el-button type="success" style="margin-left: 5px;" @click="resetParam">重置</el-button>
- <el-button type="success" @click="add">新增</el-button>
- </div>
- <el-table :data="tableData" style="height: 100%;"
- :header-cell-style="{background:'#92b5b6', color:'#221e1d'}"
- border>
- <el-table-column prop="id" label="ID" >
- </el-table-column>
- <el-table-column prop="userNo" label="账号">
- </el-table-column>
- <el-table-column prop="userName" label="名字">
- </el-table-column>
- <el-table-column prop="age" label="年龄">
- </el-table-column>
- <el-table-column prop="sex" label="性别">
- <template slot-scope="scope">
- <el-tag
- :type="scope.row.sex === 1 ? 'primary' : 'success'"
- disable-transitions>{{scope.row.sex === 1 ? '男' : '女'}}</el-tag>
- </template>
- </el-table-column>
- <el-table-column prop="roleId" label="角色">
- <template slot-scope="scope">
- <el-tag
- :type="scope.row.roleId === 0 ? 'danger' : (scope.row.roleId === 1 ? 'primary' : 'success')"
- disable-transitions>{{scope.row.roleId === 0 ? '超级管理员' : (scope.row.roleId === 1 ? '管理员' : '用户')}}</el-tag>
- </template>
- </el-table-column>
- <el-table-column prop="phone" label="电话">
- </el-table-column>
- <el-table-column prop="operate" label="操作">
- <template slot-scope="scope">
- <el-button type="success" @click="update(scope.row)" style="margin-right:10px;">编辑</el-button>
- <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.id)">
- <el-button type="danger" slot="reference">删除</el-button>
- </el-popconfirm>
- </template>
- </el-table-column>
- </el-table>
- <el-pagination
- @size-change="handleSizeChange"
- @current-change="handleCurrentChange"
- :current-page="pageNum"
- :page-sizes="[1, 2, 10, 20]"
- :page-size="pageSize"
- layout="total, sizes, prev, pager, next, jumper"
- :total="total">
- </el-pagination>
- <el-dialog
- title="新增用户"
- :visible.sync="dialogVisible"
- width="30%"
- :before-close="handleClose"
- center>
- <el-form ref="form" :rules="rules" :model="form" label-width="80px">
- <el-form-item label="账号" prop="userNo">
- <el-col :span="20">
- <el-input v-model="form.userNo"></el-input>
- </el-col>
- </el-form-item>
- <el-form-item label="名字" prop="userName">
- <el-col :span="20">
- <el-input v-model="form.userName"></el-input>
- </el-col>
- </el-form-item>
- <el-form-item label="密码" prop="password">
- <el-col :span="20">
- <el-input v-model="form.password"></el-input>
- </el-col>
- </el-form-item>
- <el-form-item label="年龄" prop="age">
- <el-col :span="20">
- <el-input v-model="form.age"></el-input>
- </el-col>
- </el-form-item>
- <el-form-item label="性别">
- <el-radio-group v-model="form.sex">
- <el-radio label="1">男</el-radio>
- <el-radio label="2">女</el-radio>
- </el-radio-group>
- </el-form-item>
- <el-form-item label="电话" prop="phone">
- <el-col :span="20">
- <el-input v-model="form.phone"></el-input>
- </el-col>
- </el-form-item>
- </el-form>
- <span slot="footer" class="dialog-footer">
- <el-button @click="dialogVisible = false">取 消</el-button>
- <el-button type="primary" @click="save">保 存</el-button>
- </span>
- </el-dialog>
- </div>
- </template>
-
- <script>
-
- export default {
- name: "MainPart",
- data() {
- //判断年龄
- let checkAge = (rule, value, callback) => {
- if(value > 150){
- callback(new Error('年龄输入过大'));
- }else{
- callback();
- }
- };
-
- //验证账号唯一性
- let checkDuplicate = (rule, value, callback) => {
- //修改时,不验证账号
- if(this.form.id){
- return callback();
- }
- this.$axios.get(this.$httpUrl + '/user/findByUserNo?userNo=' + this.form.userNo).then( res=> {
- //console.log(res);
- if(res.data.code !==200){
- callback();
- }else{
- callback(new Error('账号已经存在'));
- }
- })
- };
- return {
- tableData: [], //列表数据
- pageNum:1, //当前页码
- pageSize:10, //每页数量
- total:0, //总记录数
- userName:'', //查询名字输入框
- sex:'', //查询选择性别
- sexList:[
- { value:'1',label:'男'},
- { value:'2',label:'女'}
- ], //性别下拉框绑定
- dialogVisible: false, //模态输入框是否显示
- form:{
- id:'',
- userNo:'',
- userName:'',
- password:'',
- age:'',
- phone:'',
- sex:'1',
- roleId:'2'
- }, //表单中的输入项
- //验证规则
- rules: {
- userNo: [
- { required: true, message: '请输入账号', trigger: 'blur' },
- { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
- { validator: checkDuplicate ,trigger:'blur'}
- ],
- userName: [
- { required: true, message: '请输入名字', trigger: 'blur' },
- { min: 1, max: 20, message: '长度在 1 到20 个字符', trigger: 'blur' }
- ],
- password: [
- { required: true, message: '请输入密码', trigger: 'blur' }
- ],
- age: [
- { required: true, message: '请输入年龄', trigger: 'blur' },
- { min:1, max:3, message: '年龄在1到3位数之间',trigger: 'blur'},
- { validator: checkAge ,trigger:'blur'}
- ],
- phone: [
- { required: true, message: '请输入电话', trigger: 'blur' },
- { pattern:/^1[3|4|5|6|7|8|9][0-9]\d{8}/, message: '手机号码格式不正确', trigger: 'blur'}
- ]
- }
- }
- },
- methods:{
- //删除按钮
- handleDelete(id){
- this.$axios.get( this.$httpUrl + '/user/delete?id=' + id).then(res => {
- //console.log(res);
- if(res.data.code ===200)
- {
- this.$message({
- message: '删除成功',
- type: 'success'
- });
- this.loadPost();
- }else {
- this.$message.error('删除失败');
- }
- });
- },
- //修改按钮
- update(row){
- //console.log(row);
- //赋值到表单
- //显示对话框
- this.dialogVisible = true;
- //异步赋值
- this.$nextTick( ()=> {
- this.form.id = row.id;
- this.form.userNo = row.userNo;
- this.form.userName = row.userName;
- this.form.password = row.password;
- this.form.age = row.age +''; //数字转字符,才显示
- this.form.phone = row.phone;
- this.form.sex = row.sex + '';
- this.form.roleId = row.roleId;
- });
- },
- //重置新增表单
- resetForm() {
- this.$refs.form.resetFields();
- },
- doUpdate(){
- this.$axios.post( this.$httpUrl + '/user/update',this.form).then(res => {
- //console.log(res);
- if(res.data.code ===200)
- {
- this.$message({
- message: '更新成功',
- type: 'success'
- });
- //关闭对话框
- this.dialogVisible = false;
- this.loadPost();
- }else {
- this.$message.error('更新失败');
- }
- });
- },
- doSave(){
- this.$axios.post( this.$httpUrl + '/user/save',this.form).then(res => {
- //console.log(res);
- if(res.data.code ===200)
- {
- this.$message({
- message: '新增成功',
- type: 'success'
- });
- //关闭对话框
- this.dialogVisible = false;
- this.loadPost();
- }else {
- this.$message.error('新增失败');
- }
- });
- },
- //保存数据
- save(){
- //保存之前,先验证
- this.$refs.form.validate((valid) => {
- //通过验证
- if (valid) {
- if(this.form.id){
- //修改,保存
- this.doUpdate();
- }else{
- //新增,保存
- this.doSave();
- }
- } else {
- //验证未通过
- return false;
- }
- });
- },
- //新增对话框关闭按钮
- handleClose() {
- this.dialogVisible = false;
- },
- //新增按钮
- add(){
- this.dialogVisible = true;
- //打开新增窗口时,将之前的内容清除
- this.$nextTick(() =>{
- this.resetForm();
- });
- },
- //重置按钮
- resetParam(){
- this.userName = '';
- this.sex = '';
- this.loadPost();
- },
- //每页数量发生变化
- handleSizeChange(val) {
- //console.log(`每页 ${val} 条`);
- this.pageNum = 1;
- this.pageSize = val;
- this.loadPost();
- },
- //当前页码发生变化
- handleCurrentChange(val) {
- //console.log(`当前页: ${val}`);
- this.pageNum = val;
- this.loadPost();
- },
- //get方式加载数据
- loadGet(){
- this.$axios.get( this.$httpUrl +'/user/listPage').then (res => {
- //console.log(res);
- if(res.data.code ===200)
- {
- this.tableData = res.data.data;
- }else {
- alert('获取数据失败');
- }
- })
- },
- //post方式加载数据
- loadPost(){
- this.$axios.post( this.$httpUrl + '/user/listPage',{
- pageSize: this.pageSize,
- pageNum : this.pageNum,
- param:{
- name: this.userName, //查询的名字
- sex: this.sex //查询性别
- }
- }).then(res => {
- //console.log(res);
- if(res.data.code ===200)
- {
- //列表数据
- this.tableData = res.data.data;
- //总记录数
- this.total = res.data.total;
- }else {
- alert('获取数据失败');
- }
- })
- }
- },
- created(){
- //this.loadGet();
- this.loadPost();
- }
- }
- </script>
-
- <style scoped>
-
- </style>

赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。