实现了后台的数据库的增删改查之后,我们需要在前端对接相关功能,所使用的工具是axios
在控制台输入:
E:\Spring_Vue管理系统\springboot\vue>npm i axios -S
下载好之后,在src中新建一个utils包,导入request.js用来请求数据
import axios from 'axios'
const request = axios.create({
baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
报错:Uncaught (in promise) Error: Network Error at createError(axios跨域问题)
解决方法:可以在前端修改,也可以修改后端(建议)
在CrosConfig中配置:
package com.example.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
报错:Request failed with status code 400
错误原因:参数不匹配
解决方法:检查参数,并修改正确参数
前端查数据:
在main.js中引入request.js
import request from "@/utils/request";
Vue.prototype.request=request
修改data()引入参数,修改load请求页面, 查询数据
import request from "@/utils/request";
export default {
name: 'Home',
data() {
return {
tableData: [],
total: 0,
pageNum: 1,
pageSize: 2,
username: "",
email: "",
address: "",
msg: "hello 阿晴",
collapseBtnClass: 'el-icon-s-fold',
isCollapse: false,
sideWidth: 200,
logoTextShow: true,
headerBg: 'headerBg'
}
},
load() {
request.get("http://localhost:9090/user/page",{
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
username: this.username,
email: this.email,
address: this.address
}
}).then(res => {
console.log(res)
this.tableData = res.records
this.total = res.total
})
},
reset(){
this.username= ""
this.email = ""
this.address = ""
this.load()
}
}
新增:
导入对话框框架:
<el-dialog title="用户信息" :visible.sync="dialogFormVisible">
<el-form label-width="120">
<el-form-item label="用户名">
<el-input v-model="form.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵称">
<el-input v-model="form.nickname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="form.email" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
</div>
</el-dialog>
在data()中引入参数:
data() {
return {
dialogFormVisible: false,
form: {},
}
}
添加点击事件
<div style="margin: 10px 0">
<el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i>
</el-button>
</div>
实现点击事件:
handleAdd(){
this.dialogFormVisible = true
this.form = {}
},
实现点击事件将数据绑定到后台:
save(){
request.post("http://localhost:9090/user", this.form).then(res =>{
if(res){
this.$message.success("保存成功")
this.dialogFormVisible = false
}else {
this.$message.error("保存失败")
}
})
},
报错:
Module Error (from ./node_modules/@vue/vue-loader-v15/lib/loaders/templateLoader.js):
(Emitted value instead of an instance of Error)
Errors compiling template:
duplicate attribute: @click
140| <div slot="footer" class="dialog-footer">
141| <el-button @click="dialogFormVisible = false">取 消</el-button>
142| <el-button type="primary" @click="dialogFormVisible = false" @click="save">确 定</el-button>
| ^^^^^^^^^^^^^
143| </div>
144| </el-dialog>
错误原因:组件里面使用 v-for 但是没有设置 key,会造成非唯一性问题。
解决办法:在一个组件中使用了两次@click,删掉一个即可
出现问题:主键的id为随机数
问题原因:引用了mybatis-plus组件,该组件会自动插入一个id到实体对象,
解决方法:
@Data
@TableName("sys_user")//指定数据库表名
public class User {
@TableId(value = "id",type = IdType.AUTO) //指定id,并且设定自增
private Integer id;
......}
编辑:
新增编辑事件:
handleEdit(row){
this.form = row
this.dialogFormVisible = true
},
<el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
删除:
新增删除事件:
<el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
del(id){
request.delete("/user/"+id).then(res =>{
if(res){
this.$message.success("删除成功")
this.load()
}else {
this.$message.error("删除失败")
}
})
},
添加删除二次确认(气泡二次确认):
<el-popconfirm
confirm-button-text='确定'
cancel-button-text='让我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定要删除吗?"
@confirm="del(scope.row.id)"
>
<el-button type="danger" slot="reference">删除 <i class="el-icon-remove- outline"></i></el-button>
</el-popconfirm>
批量删除:
添加多选框
<el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange">
<el-table-column
type="selection"
width="55">
</el-table-column>
......
在data中添加新的参数:
multipleSelection: [],
添加多选 框配套点击事件:
handleSelectionChange(val){
this.multipleSelection = val
},
在userController中新增批量删除接口:
@DeleteMapping("/del/batch/")
public boolean deleteBatch(@RequestBody List<Integer> ids){
return userService.removeByIds(ids);
}
添加批量删除点击事件:
<el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
批量删除逻辑:
delBatch(){
let ids = this.multipleSelection.map(v => v.id)//将[{},{},{}] =>[1,2,3],即将对象转为int数字
request.post("/user/del/batch", ids).then(res =>{
if(res){
this.$message.success("批量删除成功")
this.load()
}else {
this.$message.error("批量删除失败")
}
})
},
添加删除二次确认(气泡二次确认):
<el-popconfirm
class="ml-5"
confirm-button-text='确定'
cancel-button-text='让我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定要删除这些数据吗?"
@confirm="delBatch"
>
<el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>