ElementUi 学习(下)

小案例

学习了ElementUi、我们开始使用ElementUi和SpringBoot写一个简单的前后端分离的项目、巩固一下学习的知识

创建项目

使用vuecli4.x脚手架创建项目

1
vue create elementui_users

20200715205406.png

需要安装 Vue-Router、之后安装ElementUi

1
npm i element-ui -S

继续安装axios用于发送网络请求

1
npm install axios --save

编辑main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Vue from 'vue'
import App from './App.vue'
import router from './router'

//导入axios
import axios from "axios"

//导入ElementUi
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false

//给 axios 取别名
Vue.prototype.$http = axios

//使用ElementUi
Vue.use(ElementUI)

new Vue({
router,
netder: h => h(App)
}).$mount('#app')

基本创建

这个项目需要导航栏、我们需要学习一下

el-menu创建导航菜单、通过:default-active绑定默认激活项,el-menu-item为菜单项、index的值与:default-active的值绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<el-menu :default-active="activeIndex" mode="horizontal">
<el-menu-item index="1">处理中心</el-menu-item>
<el-menu-item index="2">订单管理</el-menu-item>
<el-menu-item index="3">消息中心</el-menu-item>
</el-menu>

<script>
export default {
data(){
return {
//代表默认选择的项
activeIndex: '1'
}
}
}
</script>

官网: https://element.eleme.cn/#/zh-CN/component/menu

components下创建Nav.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<el-menu :default-active="activeIndex" mode="horizontal" @select="handleSelect">
<el-menu-item index="/index">主页</el-menu-item>
<el-menu-item index="/users">用户管理</el-menu-item>
<el-menu-item index="/msgs">消息中心</el-menu-item>
<el-menu-item index="/orders">订单管理</el-menu-item>
</el-menu>
</template>

<script>
export default {
name: "Nav",
data() {
return {
activeIndex: this.$route.path
};
},
methods: {
handleSelect(key, keyPath) {
this.$router.push(key)
}
}
}
</script>

<style scoped>

</style>

编辑App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div id="app">
<Nav/>
<router-view/>
</div>
</template>

<script>

import Nav from './components/Nav'

export default {
name: "App",
data(){
return{

}
},
components:{
Nav
}
}
</script>

<style>

</style>
页面创建

views目录下创建

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h2>我是主页</h2>
</template>

<script>
export default {
name: "Index"
}
</script>

<style scoped>

</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h2>消息</h2>
</template>

<script>
export default {
name: "Msg"
}
</script>

<style scoped>

</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h2>订单</h2>
</template>

<script>
export default {
name: "Order"
}
</script>

<style scoped>

</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<h2>用户</h2>
</template>

<script>
export default {
name: "User"
}
</script>

<style scoped>3213

</style>

配置路由

编辑router/index.js

但是为避免之后使用this.$router.push重复点击一个路由报错

20200715213324.png

所以我们要在router/index.js添加、问题参考: https://blog.csdn.net/qq_41687299/article/details/106869943

1
2
3
4
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}

继续编辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import Vue from 'vue'
import VueRouter from 'vue-router'

import Index from "../views/Index"
import User from "../views/User"
import Order from "../views/Order"
import Msg from "../views/Msg"

Vue.use(VueRouter)

//防止路由重复
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}

const routes = [
{
path: "/",
//默认页面重定向到index
redirect: "/index"
},
{
path: "/index",
name: "index",
component: Index
},
{
path: "/users",
name: "users",
component: User
},
{
path: "/msgs",
name: "msgs",
component: Msg
},
{
path: "/orders",
name: "orders",
component: Order
}
]

const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})

export default router

npm run serve运行项目

20200715215936.gif

如上图所示、没有报错就说明成功了

页面编辑

主页

添加一个轮播图效果

el-carousel创建轮播图、el-carousel-item创建每一项

  • height指定高度

el-image创建图片

  • :src绑定图片
  • fit:确定图片如何适应到容器框、有fill / contain / cover / none / scale-down
  • style=""最好指定高度

官网:

所以编辑Index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<template>
<el-carousel indicator-position="outside" height="600px">
<el-carousel-item v-for="img in imgList" :key="img">
<el-image
style="height: 600px"
:src="img"
fit="cover"
></el-image>
</el-carousel-item>
</el-carousel>
</template>

<script>
export default {
name: "Index",
data() {
return {
imgList: [
'https://cdn.jsdelivr.net/gh/zykjofficial/zykjimg/anime/anime0.png',
'https://cdn.jsdelivr.net/gh/zykjofficial/zykjimg/anime/anime1.png',
'https://cdn.jsdelivr.net/gh/zykjofficial/zykjimg/anime/anime2.png',
'https://cdn.jsdelivr.net/gh/zykjofficial/zykjimg/anime/anime3.png'
]
}
}
}
</script>

<style scoped>

</style>
用户管理

使用Table表格进行创建、用到了自定义表头自定义列模板相关内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<template>
<div>
<el-table
:data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
style="width: 100%">
<el-table-column
label="编号"
width="180">
<template slot-scope="scope">
<span style="margin-left: 10px">{{ scope.row.id }}</span>
</template>
</el-table-column>
<el-table-column
label="姓名"
width="180">
<template slot-scope="scope">
<el-popover trigger="hover" placement="top">
<p>姓名: {{ scope.row.name }}</p>
<p>住址: {{ scope.row.address }}</p>
<div slot="refenetce" class="name-wrapper">
<el-tag size="medium">{{ scope.row.name }}</el-tag>
</div>
</el-popover>
</template>
</el-table-column>
<el-table-column label="性别" prop="sex"></el-table-column>
<el-table-column label="生日" prop="birth"></el-table-column>
<el-table-column label="地址" prop="address"></el-table-column>
<el-table-column
align="right">
<template slot="header" slot-scope="scope">
<el-input
v-model="search"
size="mini"
placeholder="输入姓名进行搜索"/>
</template>
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">编辑
</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除
</el-button>
</template>
</el-table-column>
</el-table>
<el-button type="success" size="mini">添加</el-button>
</div>
</template>

<script>
export default {
name: "User",
data() {
return {
search:'',
tableData: [{
id: 1,
name: '王小虎',
sex: '男',
birth: '2000-05-02',
address: '上海市普陀区金沙江路 1 弄'
}, {
id: 2,
name: '王大虎',
sex: '男',
birth: '1998-03-12',
address: '上海市普陀区金沙江路 2 弄'
}, {
id: 3,
name: '王小妞',
sex: '女',
birth: '2001-06-02',
address: '上海市普陀区金沙江路 3 弄'
}, {
id: 4,
name: '王大妞',
sex: '女',
birth: '1999-12-23',
address: '上海市普陀区金沙江路 3 弄'
}]
}
},
methods: {
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
}
}
}
</script>

<style scoped>

</style>

后台搭建

数据库

通过软件Navicat Premium创建一个elementui_users数据库

创建 t_users

1
2
3
4
5
6
7
8
CREATE TABLE `t_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(80) DEFAULT NULL,
`birth` timestamp NULL DEFAULT NULL,
`sex` varchar(4) DEFAULT NULL,
`address` varchar(120) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SpringBoot项目

使用IDEA搭建SpringBoot项目

使用最新版SpringBoot、如果有问题就降低版本

我们在pom.xml->dependencies添加一个druid依赖

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>

编辑src\main\resources\application.properties文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
## 端口号
server.port=8989
## 应用名
spring.application.name=elementui_users
## API的上下文路径
server.servlet.context-path=/

#数据库相关
## 使用alibaba的druid数据源
sping.datasource.type=com.alibaba.druid.pool.DruidDataSource
## 数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## 数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/elementui_users?useSSL=false&useUnicode=true&charactenetcoding=utf8&serverTimezone=UTC
## 用户名
spring.datasource.username=root
## 密码
spring.datasource.password=

## mybatis
## mapper位置
mybatis.mapper-locations=classpath:com/zykj/mapper/*.xml
#别名
mybatis.type-aliases-package=com.zykj.entity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.zykj.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
//链式编程
@Accessors(chain = true)
public class User {
private String id;
private String name;
//需要格式化一下日期
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birth;
private String sex;
private String address;
}
1
2
3
4
5
6
7
8
9
10
11
package com.zykj.dao;

import com.zykj.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserDao {
public List<User> findAll();
}

接着在src\main\resources\com\zykj\mapper\创建UserDao.xml

1
2
3
4
5
6
7
8
9
<?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.zykj.dao.UserDao">

<select id="findAll" resultType="User">
select id,name,birth,sex,address from t_users
</select>

</mapper>
1
2
3
4
5
6
7
8
9
package com.zykj.service;

import com.zykj.entity.User;

import java.util.List;

public interface UserService {
public List<User> findAll();
}

实现类UserServiceImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.zykj.service;

import com.zykj.dao.UserDao;
import com.zykj.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

@Autowired
private UserDao userDao;

@Override
// 支持当前事务,如果当前没有事务,就以非事务方式执行。
@Transactional(propagation = Propagation.SUPPORTS)
public void save(User user) {
userDao.save(user);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.zykj.controller;

import com.zykj.entity.User;
import com.zykj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
//解决跨域问题
@CrossOrigin
public class UserController {

@Autowired
private UserService userService;

@GetMapping("findall")
public List<User> findAll(){
return userService.findAll();
}

}

com.zykj.vo创建Result类、用于保存状态信息

1
2
3
4
5
6
7
8
9
10
11
package com.zykj.vo;

import lombok.Data;

@Data
public class Result {
//默认状态
private boolean status = true;
//返回信息
private String msg;
}

简单测试一下、在src\test\java\com\zykj下创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.zykj;

import com.zykj.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestUserService {

@Autowired
private UserService userService;

@Test
public void TestUserService() {
userService.findAll().forEach(user -> System.out.println("User: " + user));
}

}

没有报错说明运行成功

用户管理相关

查询所有用户

修改一下User.vue页面配置axios请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script>
export default {
name: "User",
data() {
return {
search:'',
tableData: []
}
},
methods: {
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
}
},
created() {
//页面创建时发起异步请求
this.$http.get( 'http://localhost:8989/user/findall').then((res)=>{
this.tableData = res.data
})
}
}
</script>
添加用户和编辑用户

编辑UserDao.java、添加

1
2
3
4
5
//保存用户
public void save(User user);

//更新用户
public void update(User user);

编辑UserDao.xml添加

1
2
3
4
5
6
7
8
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_users values (#{id},#{name},#{birth},#{sex},#{address})
</insert>

<update id="update" parameterType="User">
update t_users set name = #{name}, birth = #{birth}, sex = #{sex} , address = #{address}
where id = #{id}
</update>

编辑UserService.javaUserServiceImpl.java分别添加

1
2
3
4
5
6
// UserService.java
//保存用户
public void save(User user);

//更新用户
public void update(User user);
1
2
3
4
5
6
7
8
9
10
11
12
// UserServiceImpl.java
@Override
// 支持当前事务,如果当前没有事务,就以非事务方式执行。
@Transactional(propagation = Propagation.SUPPORTS)
public void save(User user) {
userDao.save(user);
}

@Override
public void update(User user) {
userDao.update(user);
}

编辑UserController.java、添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@PostMapping("saveOrUpdate")
public Result save(@RequestBody User user) {
Result reslut = new Result();
try {
if (StringUtils.isEmpty(user.getId())) {
userService.save(user);
reslut.setMsg("用户信息添加成功");
} else {
userService.update(user);
reslut.setMsg("用户信息更新成功");
}
} catch (Exception e) {
e.printStackTrace();
reslut.setStatus(false);
reslut.setMsg("发生错误、请稍后再试...");
}
return reslut;
}

继续修改User.vue

添加了Dialog 对话框Message 消息提示Table 表格

代码不全、只展示修改部分

问题汇总:

  • 为保证输入日期时间正确显示、需要在 el-date-picker 添加format="yyyy-MM-dd"
  • 表单验证的规则中: date 验证不能添加type='date'原因: https://blog.csdn.net/weixin_44356673/article/details/107222947
  • 方法: handleEditthis.form = {...row}; 避免数据双向绑定造成的错误(这个问题解决了一下午。。。)
  • 方法: resetForm中使用this.$refs[formName].clearValidate();清除验证,不用resetFields(对该表单项进行重置,将其值重置为初始值并移除校验结果)会重置为有数据的值。文章: https://blog.csdn.net/haidong55/article/details/90484138
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
<template>
<div>
<el-table
:data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
style="width: 100%">
...
<el-table-column
align="right">
<template slot="header" slot-scope="scope">
<el-input
v-model="search"
size="mini"
placeholder="输入姓名进行搜索"/>
</template>
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">编辑
</el-button>
...
</template>
</el-table-column>
</el-table>
...
<el-dialog @closed="closeDialog" :title="dialogTitle[title]" :visible.sync="dialogFormVisible"
:close-on-click-modal="false">
<el-form ref="addfrom" :model="form" label-suffix=":" :rules="rules">
<el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="生日" :label-width="formLabelWidth" prop="birth">
<el-date-picker type="date" placeholder="选择日期" v-model="form.birth" value-format="yyyy-MM-dd"
style="width: 100%;"></el-date-picker>
</el-form-item>
<el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
<el-radio-group v-model="form.sex">
<el-radio label="男"></el-radio>
<el-radio label="女"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
<el-input type="textarea" v-model="form.address"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="AddSubmit('addfrom')">{{ dialogTitle[title] }}</el-button>
<el-button @click="resetForm('addfrom')">重置</el-button>
</div>
</el-dialog>
</div>
</template>

<script>
export default {
name: "User",
data() {
return {
title: "",
dialogTitle: {
add: "添加",
update: "编辑",
},
//...
search: '',
tableData: [],
dialogFormVisible: false,
form: {
name: '',
birth: '',
sex: '男',
address: ''
},
formLabelWidth: '120px',
rules: {
name: [
{required: true, message: '请输入姓名', trigger: 'blur'},
{min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
],
// 不能填写type 原因: https://blog.csdn.net/weixin_44356673/article/details/107222947
birth: [
{required: true, message: '请选择日期', trigger: 'blur'}
],
sex: [
{required: true, message: '请选择性别', trigger: 'blur'}
],
address: [
{required: true, message: '请填写地址', trigger: 'blur'}
]
}
}
},
methods: {
//...
saveUserInfo() {
this.resetForm('form')
this.dialogFormVisible = true;
this.title = "add"
},
handleEdit(index, row) {
this.resetForm('form')
this.dialogFormVisible = true;
this.title = "update";
// 避免数据双向绑定造成的错误
this.form = {...row};
},
// ...
AddSubmit(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$http.post("http://localhost:8989/user/saveOrUpdate", this.form).then((res) => {
if (res.data.status) {
this.$message({
message: "恭喜你" + res.data.msg,
type: "success"
})
//清空表单
this.form = {}
//关闭消息框
this.dialogFormVisible = false
//重新获取数据
this.findAllTableData()
} else {
this.$message.error(res.data.msg);
}
})
} else {
this.$message.error("请填写完整数据!")
return false;
}
});
},
resetForm(formName) {
if (this.$refs[formName] !== undefined) {
this.$refs[formName].clearValidate();
}
this.form = {sex: '男'}
},
// ...
closeDialog() {
this.resetForm('addfrom');
}
},
created() {
this.findAllTableData();
}
}
</script>

<style scoped>
.el-button {
margin: 5px;
}
</style>
删除用户

编辑UserDao.java、添加

1
2
//删除用户
public void delete(String id);

编辑UserDao.xml添加

1
2
3
<delete id="delete" parameterType="String">
delete from t_users where id = #{id}
</delete>

编辑UserService.javaUserServiceImpl.java分别添加

1
2
3
// UserService.java
//删除用户
public void delete(String id);
1
2
3
4
5
// UserServiceImpl.java
@Override
public void delete(String id) {
userDao.delete(id);
}

编辑UserController.java、添加

1
2
3
4
5
6
7
8
9
10
11
12
13
@GetMapping("delete")
public Result delete(String id){
Result reslut = new Result();
try{
userService.delete(id);
reslut.setMsg("用户信息删除成功");
}catch (Exception e){
e.printStackTrace();
reslut.setStatus(false);
reslut.setMsg("用户信息删除失败、请稍后再试...");
}
return reslut;
}

继续修改User.vue

添加了Popconfirm 气泡确认框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<template>
<div>
<el-table
:data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
style="width: 100%">
...
<el-table-column
align="right">
...
<template slot-scope="scope">
...
<el-popconfirm
confirmButtonText='好的'
cancelButtonText='不用了'
icon="el-icon-info"
iconColor="red"
title="确定删除用户吗?"
@onConfirm="handleDelete(scope.$index, scope.row)">
<el-button slot="refenetce" size="mini" type="danger">删除</el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
...
</div>
</template>

<script>
export default {
name: "User",
data() {
return {
// ...
}
},
methods: {
// ...
handleDelete(index, row) {
this.$http.get("http://localhost:8989/user/delete", {
params: {
id: row.id
}
}).then((res) => {
if (res.data.status) {
this.$message({
message: res.data.msg,
type: "success"
})
//重新获取数据
this.findAllTableData()
} else {
this.$message.error(res.data.msg);
}
})
}
//...
},
created() {
this.findAllTableData();
}
}
</script>

分页效果

编辑UserDao.java、添加

1
2
3
4
5
6
//删除用户
//分页查询
public List<User> findByPage(@Param("start") Integer start,@Param("rows") Integer rows);

//查询总数
public Long findTotals();

编辑UserDao.xml添加

1
2
3
4
5
6
7
<select id="findByPage" resultType="User">
select id,name,birth,sex,address from t_users limit #{start},#{rows}
</select>

<select id="findTotals" resultType="Long">
select count(id) from t_users
</select>

编辑UserService.javaUserServiceImpl.java分别添加

1
2
3
4
5
6
// UserService.java
//分页查询
public List<User> findByPage(Integer pageNow, Integer rows);

//查询总数
public Long findTotals();
1
2
3
4
5
6
7
8
9
10
11
// UserServiceImpl.java
@Override
public List<User> findByPage(Integer pageNow, Integer rows) {
int start = (pageNow - 1) * rows;
return userDao.findByPage(start, rows);
}

@Override
public Long findTotals() {
return userDao.findTotals();
}

编辑UserController.java、添加

1
2
3
4
5
6
7
8
9
@GetMapping("findByPage")
public Map<String, Object> findByPage(@RequestParam(value = "pageNow",defaultValue = "1") Integer pageNow,@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize) {
Map<String, Object> result = new HashMap<>();
List<User> users = userService.findByPage(pageNow, pageSize);
Long totals = userService.findTotals();
result.put("users", users);
result.put("total", totals);
return result;
}

继续修改User.vue

添加了Pagination 分页

一定要设置page-sizepage-sizes否则不能自定义显示的页数。。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<template>
<div>
...
<el-row :gutter="20">
<el-col :span="8" :offset="14">
<el-pagination
layout="prev, pager, next, jumper, total, sizes"
:page-size="size"
:curnett-page="pageNow"
:page-sizes="[1,3,5,7,9]"
@size-change="findSize"
@curnett-change="findPage"
:total="totalSize">
</el-pagination>
</el-col>
</el-row>
...
</div>
</template>

<script>
export default {
name: "User",
data() {
return {
//...
totalSize: 0,
pageNow: 1,
size: 5,
//...
}
},
methods: {
findSize(size) {
this.size = size;
this.findAllTableData(this.pageNow, size)
},
findPage(page) {
this.pageNow = page;
this.findAllTableData(page, this.size)
},
//...
findAllTableData(page, size) {
page = page == null ? 1 : page;
size = size == null ? 5 : size;
this.$http.get('http://localhost:8989/user/findByPage', {
params: {
pageNow: page,
pageSize: size
}
}).then((res) => {
this.tableData = res.data.users
this.totalSize = res.data.total
})
},
//...
},
//...
}
</script>

打包

到这里一个简单的ElementUi项目就完成了、需要打包Vue项目、在Vue项目根目录运行

1
npm run build

将生成的项目dist目录下的 static目录index.html放到SpringBoot项目src\main\resources\static

编辑src\main\resources\application.properties文件、添加

1
spring.resources.static-locations=classpath:/static/

之后直接运行SpringBoot项目访问 http://localhost:8989 就可以了.