这篇文章的目的是教会大家如何使用Axios请求后端数据,将拿到的后端数据JSON显示到ElementUi 的表格中,完成标准的分页,和增删改查。
ElmentUI是一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库,
是由大名鼎鼎的饿了么前端团队开发的。
想要了解更多可以去饿了么框架官网
饿了么框架
axios是Vue官方推荐的AJAX请求工具,它的Api比Jquery以及原生fetch简单,使用起来非常的方便。
我这里使用的SpringBoot + SpringDataJpa + Mysql, 其实不管后端采用什么语言编写的,只要能给前端返回准确的JSON数据就ok了,后端没有硬性要求。
我们创建一个element_ui的SpringBoot工程
在创建项目的时候添加如上依赖,这里我强调一下这里为什么用Thymeleaf,这里用Thymeleaf仅仅是返回一个视图页面。
首先我们在Mysql中建立一个数据库crud,再建立一个数据表crud表
实体类代码
@Entity
public class Crud {
private int id;
private String crudName;
private int crudAge;
private String crudHobby;
private String crudAddr;
private String crudSalary;
}
这里省略了部分代码,这里的实体类是由SpringDataJpa帮我们自动生成的。
Dao持久层代码
public interface CrudRepository extends JpaRepository<Crud,Integer> {
Page<Crud> findAll(Pageable pageable);
}
dao里面就只有一个方法,分页查询所有数据
控制器代码
@Controller
public class HomeController {
@Autowired
private CrudRepository crudRepository;
@GetMapping("/")
public String indexPage() {
return "index"; //返回一个index.html页面
}
@PostMapping("/page")
@ResponseBody
public ResponseEntity<Object> findPageAll(@RequestBody PageVO pageVO) {
Pageable pageable = PageRequest.of(pageVO.getStart(),pageVO.getLength(), Sort.Direction.ASC,"id");
Page<Crud> page = crudRepository.findAll(pageable);
return new ResponseEntity<Object>(page, HttpStatus.OK);
}
@DeleteMapping("/crud/{id}")
@ResponseBody
public ResponseEntity<Object> deleteById(@PathVariable("id") Integer id) {
if (id.equals("")) {
return new ResponseEntity<Object>("id不能为空", HttpStatus.NOT_FOUND);
}
crudRepository.deleteById(id);
return new ResponseEntity<Object>("删除成功", HttpStatus.OK);
}
@PutMapping("/updateUser")
@ResponseBody
public ResponseEntity<Object> updateById( @RequestBody Crud crud) {
if (crud != null) {
crudRepository.save(crud);
return new ResponseEntity<Object>("编辑成功", HttpStatus.OK);
}
return new ResponseEntity<Object>("编辑失败", HttpStatus.OK);
}
@PostMapping("/addCrud")
@ResponseBody
public ResponseEntity<Object> addCrud( @RequestBody Crud crud) {
if (crud != null) {
crudRepository.save(crud);
return new ResponseEntity<Object>("添加成功", HttpStatus.OK);
}
return new ResponseEntity<Object>("添加失败", HttpStatus.OK);
}
}
这里的PageVo是我自己封装的,省略get/set 方法 代码如下
public class PageVO {
private Integer start = 0; //页码
private Integer length = 10; //页数
}
application.yml 配置文件
spring:
application:
name: elment_crud
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/crud?serverTimezone=GMT%2B8
username: root
password: root
注意mysql5.7以上 驱动是com.mysql.cj.jdbc.Driver 5.7及以下是com.mysql.jdbc.Driver
这里使用的Vue不是单文件组件.vue的形式而是在html中引入了vue.js
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title>
<link rel="stylesheet" href="../index.css">
head>
<body>
<div id="app">
<el-row>
<el-button type="primary" @click="handleAdd">添加el-button>
el-row>
<el-table
:data="crud"
style="width: 100%"
height="250">
<el-table-column
fixed
prop="id"
label="编号"
width="150">
el-table-column>
<el-table-column
prop="crudName"
label="名称"
width="120">
el-table-column>
<el-table-column
prop="crudAge"
label="年龄"
width="120">
el-table-column>
<el-table-column
prop="crudSalary"
label="薪水"
width="120">
el-table-column>
<el-table-column
prop="crudHobby"
label="地址"
width="爱好">
el-table-column>
<el-table-column
prop="crudAddr"
label="地址"
width="120">
el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row,crud)">编辑el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row,crud)">删除el-button>
template>
el-table-column>
el-table>
<div class="pagination">
<el-pagination
background
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageCode"
:page-sizes="pageOption"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="totalaElemnts">
el-pagination>
div>
<div v-show="show">
<el-dialog title="用户信息" :visible.sync="dialogFormVisible">
<el-form>
<el-form-item label="昵称" :label-width="formLabelWidth">
<el-input v-model="formCrud.crudName" autocomplete="off">el-input>
el-form-item>
<el-form-item label="年龄" :label-width="formLabelWidth">
<el-input v-model="formCrud.crudAge" autocomplete="off">el-input>
el-form-item>
<el-form-item label="薪水" :label-width="formLabelWidth">
<el-input v-model="formCrud.crudSalary" autocomplete="off">el-input>
el-form-item>
<el-form-item label="爱好" :label-width="formLabelWidth">
<el-input v-model="formCrud.crudHobby" autocomplete="off">el-input>
el-form-item>
<el-form-item label="地址" :label-width="formLabelWidth">
<el-input v-model="formCrud.crudAddr" autocomplete="off">el-input>
el-form-item>
el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false" >取 消el-button>
<el-button v-show="btn_show" type="primary" @click="handleUpdate">确 定el-button>
<el-button type="primary" v-show="btn2_show" @click="add">确定添加el-button>
div>
el-dialog>
div>
div>
body>
<script src="../vue.js">script>
<script src="../index.js">script>
<script src="../axios.min.js">script>
<script>
new Vue({
el: '#app',
data() {
return {
show: false,
btn_show: false,
btn2_show: false,
crud: [],
pageCode: 0, //默认页
pageSize: 10,//每页10条
totalPage: 10 ,//总页数
pageOption: [10, 50, 100],
totalaElemnts: 100, //总记录数
dialogFormVisible:false,
formCrud: {
id: '',
crudName: '',
crudAge: '',
crudHobby: '',
crudSalary: '',
crudAddr: '',
},
formLabelWidth: '120px'
}
},
methods: {
findByPage(pageCode, pageSize) {
axios.post("http://localhost:8080/page",{
start: pageCode,
length: pageSize
}).then( (res) => {
if (res.status === 200)
this.totalPage = res.data.totalPages //总页数
this.totalaElemnts = res.data.totalElements //总记录数
this.crud = res.data.content
}).catch((err) => {
console.log(err)
})
},
handleSizeChange(val) {
this.findByPage(this.pageCode, val)
},
handleCurrentChange(val) {
this.findByPage(val, this.pageSize)
},
/**
* 删除
* @param index
* @param row
* @param crud
*/
handleDelete(index, row, crud) {
var id = crud[index].id;
axios.delete("http://localhost:8080/crud/" + id, {
}).then((res) =>{
this.findByPage(this.pageCode, this.pageSize)
}).catch((err) => {
console.log(err)
})
},
/**
* 编辑 之前回显数据
* @param index
* @param row
* @param crud
*/
handleEdit(index, row, crud) {
this.show = true
this.dialogFormVisible = true
this.btn_show = true
this.btn2_show = false
this.formCrud.id = crud[index].id
this.formCrud.crudName = crud[index].crudName
this.formCrud.crudAge = crud[index].crudAge
this.formCrud.crudSalary = crud[index].crudSalary
this.formCrud.crudHobby = crud[index].crudHobby
this.formCrud.crudAddr = crud[index].crudAddr
},
/**
* 编辑发送ajax请求
*/
handleUpdate() {
axios.put("http://localhost:8080/updateUser",{
id: this.formCrud.id,
crudName: this.formCrud.crudName,
crudAge: this.formCrud.crudAge,
crudHobby: this.formCrud.crudHobby,
crudSalary: this.formCrud.crudSalary,
crudAddr: this.formCrud.crudAddr
}).then((res) => {
//编辑成功后刷新页面
this.findByPage(this.pageCode, this.pageSize)
//关闭遮罩层
this.show = false
this.dialogFormVisible = false
console.log(1, res)
}).catch((err) => {
console.log(2, err)
})
},
/**
* 点击添加按钮的时候显示遮罩层,同时将编辑的按钮隐藏掉
*/
handleAdd() {
this.show= true
this.dialogFormVisible = true
//将双向绑定数据滞空
this.formCrud.crudName= ''
this.formCrud.crudAge = ''
this.formCrud.crudHobby = ''
this.formCrud.crudSalary = ''
this.formCrud.crudAddr = ''
//将新编辑按钮隐藏掉
this.btn_show = false
//将新增按钮显示 v-show 其实是display:none 和black操作
this.btn2_show =true
},
/**
* 新增
*/
add() {
axios.post("http://localhost:8080/addCrud",{
crudName: this.formCrud.crudName,
crudAge: this.formCrud.crudAge ,
crudHobby: this.formCrud.crudHobby,
crudSalary: this.formCrud.crudSalary,
crudAddr: this.formCrud.crudAddr
}).then((res) => {
//添加成功后从新计算总页数
this.findByPage(this.pageCode, this.pageSize)
//同时关闭遮罩层
this.show= true
this.dialogFormVisible = false
}).catch((err) => {
console.log(err)
})
}
},
created() {
this.findByPage(this.pageCode, this.pageSize)
},
})
script>
html>
这样就完成了增删改查和分页,非常简单,这里并没有使用单文件组件的方式, 推荐大家去使用单文件的组件方式去实现,单文件组件也是非常的简单,这里就不做太多的深入了,网上哪些人实现的方法太过于复杂,我按照自己的想法实现了,写代码一定要有思维,这样写代码就很轻松。
element ui 框架总体来说提供来非常多多样式,对没有css功底的程序员来说是相当不错的,极大的帮助了我们,不用花费很多的时间去写样式。
github