下载所需要的 js 文件,或者直接引用
复制src连接并访问,然后右键,另存为分别保存下来,复制到static/js文件夹下即可
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
在 static 文件夹下建立 首页 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div id="app">
<table>
<tr>
<th>序号</th><th>id</th><th>姓名</th><th>金钱</th><th>生日</th><th>操作</th>
</tr>
<!--v-for 遍历循环,多个参数用括号括起来-->
<tr v-for="(u,index) in users">
<td>{{index + 1}}</td>
<td>{{u.id}}</td>
<td>{{u.name}}</td>
<td>{{u.money}}</td>
<td>{{u.birthDay}}</td>
</tr>
</table>
</div>
<!--
引用下载好的 js 文件,也可以直接用
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
-->
<script src="js/vue.min.js"></script>
<script src="js/axios.min.js"></script>
<script>
let v = new Vue({
// 选中要渲染的元素 le
el: '#app',
// 存放需要变动的数据
data: {
// table表中用到的 users 数组数据
users: []
},
// created vue声明周期的(渲染之前阶段),此时调用方法 function 去获取渲染需要的数据
created: function () {
// get方法访问 "/selectAll" 获取数据
axios.get("/selectAll")
.then( // .then 指的是访问成功之后
resp => { // resp 是响应数据
// 这里将响应数据中的 data 赋值给 v(Vue) 中的 users
// 注意不是 v.data.users
v.users = resp.data
})
.catch(error=>{console.log(error)}) //.catch 指的是失败后,在控制台输出 error 信息
},
methods: {}
})
</script>
</body>
</html>
创建 UserMapper
package com.prictice.mybatis2.controller;
import com.prictice.mybatis2.entity.User;
import com.prictice.mybatis2.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserMapper mapper;
@GetMapping("/selectAll")
public List<User> selectAll(){
/* 当 return 集合或者自定义类 的时候
SpringMVC 会自动将其转换为 json 数据类型,
然后通过二进制文件的形式传输给浏览器 */
return mapper.selectAll();
}
}
然后启动主程序,直接访问 http://localhost:8080/
实现修改功能
index.html 中添加修改跳转 注意 :href="'/update.html?id=' + id"
<tr v-for="(u,index) in users">
<td>{{index + 1}}</td>
<td>{{u.id}}</td>
<!--可以通过这样的方式让 元素内容 附带跳转功能-->
<td><a :href="'/update.html?id='+u.id">{{u.name}}</a></td>
<td>{{u.money}}</td>
<td>{{u.birthDay}}</td>
<td>
<!--这里利用 v-bind 进行 href 拼接,点击即跳到 /update 附带 当前行对象的 id-->
<a :href="'/update.html?id='+u.id">修改</a>
</td>
</tr>
V 新建 update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改</title>
</head>
<body>
<div id="app">
<form action="">
id:<input type="text" name="id" :value="user.id" placeholder="id" readonly>
姓名:<input type="text" name="name" :value="user.name" placeholder="name">
金钱:<input type="text" name="money" :value="user.money" placeholder="money">
生日:<input type="date" name="birthDay" :value="user.birthDay" placeholder="birthDay">
<input type="button" @click="update()" value="修改">
</form>
</div>
<script src="js/vue.min.js"></script>
<script src="js/axios.min.js"></script>
<script>
let v = new Vue({
el: '#app',
data: {
// form 表中用到的 user 对象数据
user:{id:'',name:'',money:'',birthDay:''}
},
created: function () {
/* 访问的 url 是 .../update?id=1 通过 location.search 获取参数 ?id=1
通过 .split('=') 分割成 ['?id','1'] 然后通过下标 [1] 得到 id */
let id = location.search.split('=')[1]
axios.get("/selectById?id="+id)
.then(resp => {
v.user = resp.data
})
.catch(error=>{console.log(error)})
},
methods: {
}
})
</script>
</body>
</html>
C UserController
@GetMapping("selectById")
public User selectById(int id){
return mapper.selectById(id);
}
M UserMapper
@Select("select * from t_users where id = #{id}")
User selectById(int id);
直接点击 修改 或者 姓名, 实现 回显功能
V 在 update.html 中增添 修改方法
methods: {
update(){
/*这里是获取 表单数据({name1;value1,name2:value2...}) 存储到变量 data 中*/
let data = new FormData(document.querySelector("form"))
// 发送 post 请求,参数为上面的 data
axios.post("/update",data).then(resp=>{
alert(resp.data)
// 跳转到主页 '/'
location.href= '/'
}).catch(e=>{console.log(e)})
}
}
C UserController
@RequestMapping("/update")
public String update(User user){
return mapper.updateById(user)==1?"修改成功":"修改失败";
}
之前日期类用的是 LocalDate 会报错 见常见错误那块 2。
所以在这里对实体类的日期类型进行处理:
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthDay;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
参考: mybatis的Date类型。 - 陆伟 - 博客园
至此实现修改功能
实现删除功能
V index.html
第 26 行,修改 后面添加 删除
<td>
<!--这里利用 v-bind 进行 href 拼接,点击即跳到 /update 附带 当前行对象的 id-->
<a :href="'/update.html?id='+u.id">修改</a>
<!--javascript:void(0) 的意思是什么也不做,即取消 超链接a 的跳转功能-->
<a href="javascript:void(0)" @click="del(u.id)">删除</a>
</td>
methods: {
del(id) {
axios.get("/delete?id=" + id).then(r => {
alert(r.data)
location.href='/'
}).catch(e => {
console.log(e)
})
}
}
C UserController
@RequestMapping("/delete")
public String deleteById(int id){
return mapper.deleteById(id)==1?"删除成功":"删除失败";
}
至此删除功能已经实现,但是删除后采用跳转刷新不舒服。咱还是异步刷新一下,
把 created 阶段的方法抽取为 getAll():
// created vue声明周期的(渲染之前阶段),此时调用 getAll() 去获取渲染需要的数据
created(){
this.getAll()
},
methods: {
del(id) {
axios.get("/delete?id=" + id).then(r => {
alert(r.data)
this.getAll()
}).catch(e => {
console.log(e)
})
},
getAll(){
// get方法访问 "/selectAll" 获取数据
axios.get("/selectAll")
.then( // .then 指的是访问成功之后
resp => { // resp 是响应数据
// 这里将响应数据中的 data 赋值给 v(Vue) 中的 users
// 注意不是 v.data.users
v.users = resp.data
})
.catch(error => {
console.log(error)
}) //.catch 指的是失败后,在控制台输出 error 信息
}
}
流畅多了~~~
实现增加数据功能
V index.html 第34行 </table > 的下面加一个 添加的表单, methods 中添加 insert()
<!--放置一个控制插入表单显示的按钮-->
<input type="button" value="添加" @click="insert_vis=!insert_vis">
<!--插入的表单通过 insert_vis 属性来控制是否显示 (v-show)-->
<form action="" v-show="insert_vis">
<input type="text" name="name" placeholder="name">
<input type="text" name="money" placeholder="money">
<input type="date" name="birthDay" placeholder="birthDay">
<input type="button" @click="insert()" value="提交">
</form>
insert() {
let data = new FormData(document.querySelector("form"))
axios.post("/insert", data).then(r => {
alert(r.data);
this.getAll()
}).catch(e => console.log(e))
}
C UserController
@RequestMapping("/insert")
public String insert(User user){
return mapper.insert(user)==1?"插入成功":"插入失败";
}
至此,最基本的增删改查就完成啦 ~~~
常见错误排查
1. Uncaught ReferenceError: Vue is not defined
vue.js 文件没有导入好, 先确认好已经导入,然后刷新 maven
2. Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'user' on field 'birthDay': rejected value [2022-03-02];
实体类 user 中的 birthDay 字段 拒绝赋值 '2022-03-02' 修改注意修改字段类型