由于是首次使用Element UI 进行前后端分离式的练习,在此做下记录,以供以后参考。
问题一:
问题背景: 当前端利用Element UI 组件建立好表单以后需要向后端获取数据来展现在浏览器上,此时就需要进行前后端通信来实现数据的交互。
问题解决:
由于需要前后端实现通信,那么可以采用 vue-axios的方式来解决,但在此之前需要引入vue-resource库,引入方式:npm i vue vue-resource --save-dev。
然后就可以利用this.http.post() 来进行数据交互。
this.$http.get()的使用:
this.$http.get('地址',{params: {参数}}).then(function(res) {
console.log(res)
// 响应成功回调
},function(res) {
console.log(res)
// 响应错误回调
})
举例说明
this.$http.get("http://localhost:8081/users/deleteUser", {params:{uid:row.id}}).then(res => {
if (res.data.status == true) {
this.$message({
message: '恭喜你'+res.data.result,
type: 'success'
});
// 清空表单信息
this.form = {};
//隐藏表单
this.show = false;
// 刷新表单
this.findAllTableMsg();
} else {
this.$message.error(res.data.result);
}
}
在上述例子中get里面的‘地址’和参数还可以写在一起:
this.$http.get("http://localhost:8081/users/deleteUser?uid=" +row.id).then(res => {
this.$http.post()使用:
和get不同的是,post请求中传递的参数是不需要加params的,同时也会多一个选项emulateJSON
设置emulateJSON:true的条件,此时如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。启用该选项后,请求会以application/x-www-form-urlencoded作为Content-Type,就像普通的HTML表单一样,而不是JSON格式。
如果你没有设置问true,那么此时后端接收的需要加上 @RequestBody注解
this.$http.post('地址',{参数},{emulateJSON:true}).then( function(res) { console.log(res.data) })
举例说明
this.$http.post(this.url+tempUrl,this.form).then(res => {
// 打印后端返回的对象
console.log(res.data)
// 打印后端对象中的具体数据
console.log(res.data.result)
if (res.data.status == true) {
this.$message({
message: '恭喜你'+res.data.result,
type: 'success'
});
// 清空表单信息
this.form = {};
//隐藏表单
this.show = false;
// 刷新表单
this.findAllTableMsg();
} else {
this.$message.error(res.data.result);
}
})
后端代码
/**
* 添加TUsers对象
* @param tUsers 传来的json格式的对象
* @return 返回R对象,是否添加成功
*/
@PostMapping("/insertUsers")
public R InsertUsers(@RequestBody TUsers tUsers){
System.out.println("tUsers = " + tUsers);
Integer ans=tUsersService.insertUsers(tUsers);
if(ans==1){
return new R(null,"添加数据成功!!!",true);
}
return new R(null,"添加数据失败!!!",false);
}
问题二 问题背景:当利用日期组件时输入的日期格式传输过去后,发现后端接收日期为null,已经排除数据不能传输的问题。其余数据可以正常保存。
问题解决:Element UI 组件中日期格式是data格式,后端实例对象中的格式也是Timestamp格式,但是数据库中的格式是 Timestamp,此时需要进行时间格式的转换
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Timestamp date;
当在后端转换时间格式后又发现所选择的时间和保存的时间相差一天,此时需要在前端代码对应的组件中的属性加入
value-format="yyyy-MM-dd" 既可以解决问题。
<el-form-item label="生日">
<el-col :span="5">
<el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.brith" style="width: 80%;">
</el-date-picker>
</el-col>
</el-form-item>