使用axios套接口

目的:后端暴露接口给前端,前端采用vue框架,使用axios将后端数据显示在前端

例子1 获取用户的信息

1
2
3
4
5
//首先在data中定义一个空字符串
data() {
return {
comInfo: '',
}
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
//将后端的数据绑定到前面定义的comInfo字段中
methods: {
getUserInfo: function () {
var self = this;
//sessionStorage里取出token;
var authorization = sessionStorage.getItem("authorization");
//获取用户
let user = sessionStorage.getItem("user");
user = JSON.parse(user);
//后端接口
var url = this.HOME + "user/get/" + user.id;
var qs = require('qs');
this.$axios
.post(url,
{
headers: {
authorization: authorization,
},
})
.then(function (res) {
self.comInfo = res.data.data;
})
.catch(function (error) {
console.log(error)
})
}
1
2
3
<p><span class="s_line"></span>&nbsp;&nbsp;&nbsp;原邮箱地址</p>
<!--取数据的时候就用{{定义的字符串.想要获取的字段名}}-->
<p class="this_number">{{comInfo.email}}</p>

例子2 正则限制input框内内容

1
2
3
4
5
/*修改邮箱*/
var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
if (!reg.test(this.input9)) {
alert("邮箱输入有误!");
return false;

例子3 vue中$refs的基本用法

在前面input框中绑定ref,如

1
2
3
4
5
6
<el-input
ref="inputName"
v-model="comInfo.name"
style="width: 90px;height: 20px;"
:placeholder="comInfo.name"
>

使用this.$refs.inputName.value可以取出该input框中输入的内容

1
2
3
4
5
6
7
8
9
10
data: JSON.stringify({
"id": sessionStorage.getItem("userId"),
"name": this.$refs.inputName.value,
"idCardNo": this.$refs.inputIdCardNo.value,
"province": this.$refs.inputProvince.value,
"city": this.$refs.inputCity.value,
"area": this.$refs.inputArea.value,
"address": this.$refs.inputAddress.value,

})

例子4 整理一个比较完整的$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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//保存
submit() {
if (this.$refs.inputName.value == null || this.$refs.inputName.value == '') {
alert("姓名不能为空!");
return false;
}
if (this.$refs.inputIdCardNo.value == null || this.$refs.inputIdCardNo.value == '') {
alert("身份证不能为空!");
return false;
}
this.$axios({

method: "post",
url: this.HOME + "user/updateUser",
headers: {
"content-type": "application/json;charset=UTF-8",
"token": sessionStorage.getItem("authorization")
},
data: JSON.stringify({
"id": sessionStorage.getItem("userId"),
"name": this.$refs.inputName.value,
"idCardNo": this.$refs.inputIdCardNo.value,
"province": this.$refs.inputProvince.value,
"city": this.$refs.inputCity.value,
"area": this.$refs.inputArea.value,
"address": this.$refs.inputAddress.value,

})
})
.then(result => {
console.log(result);
if (result.data.resultCode != "200") alert("错误:" + msg.message);
if (result.data.resultCode == "200") {
this.getUserInfo();
alert("修改成功");
}

const msg = !this.$common.isNull(result.data.data)
? result.data.data
: "";

}
)
.catch(err => {
alert("错误:获取数据异常" + err);
})
;
}
},
赏个🍗吧
0%