一、axios安裝
正常情況下使用腳手架vue-cli創建的項目都集成了axios插件,無需安裝,如果需要安裝請使用npm install axios --save命令進行安裝。
二、axios常見5種請求方法
1、get請求
用於獲取數據。
2、post請求
用於提交數據(新建)、包括表單提交及文件上傳。
3、put請求
用於更新數據(修改),將所有數據都推送到后端。
4、patch請求
用於更新數據(修改),只將修改的數據推送到后端。
5、delete請求
用於刪除數據。
三、代碼示例
首先導入axios,導入代碼:
import axios from 'axios'
1、get方法
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
axios.get(
'接口地址'
, {
params: {
id:
12
,
//請求參數
},
}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'get'
,
//請求方法
params: {
id:
12
,
//請求參數
},
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|
2、post請求
1
|
post方式請求,參數有兩種形式:
|
1
|
1
、form-data表單提交(圖片上傳,文件上傳)
|
1
|
2
、applicition/json
|
1)applicition/json請求方式代碼如下:
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
let data={
id:
12
}
axios.post(
'接口地址'
, data}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'post'
,
//請求方法
data: data,
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|
2)formData請求方式代碼如下:
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
let data = {
id:
12
}
let formData =
new
formData()
for
(let key in data){
fromData.append(key,data[key])
}
axios.post(
'接口地址'
, fromData}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'post'
,
//請求方法
data: fromData,
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|
3、put請求
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
let data = {
id:
12
}
axios.put(
'接口地址'
, data}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'put'
,
//請求方法
data: data,
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|
4、patch請求
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
let data = {
id:
12
}
axios.patch(
'接口地址'
, data}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'patch'
,
//請求方法
data: data,
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|
5、delete請求
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
|
<script>
import
axios from
'axios'
export
default
{
name:
'get請求'
,
components: {},
created() {
//寫法一
let data = {
id:
12
}
//url傳遞參數
axios.delete(
'接口地址'
, {
parmas:{
id:
12
}
}).then(
(res) => {
//執行成功后代碼處理
}
)
//post方式傳遞參數
axios.delete(
'接口地址'
, {
data:{
id:
12
}
}).then(
(res) => {
//執行成功后代碼處理
}
)
//寫法二
axios({
method:
'patch'
,
//請求方法
parmas:{
id:
12
},
url:
'后台接口地址'
,
}).then(res => {
//執行成功后代碼處理
})
}
}
</script>
|