vue项目中使用axios请求网络
约 570 字大约 2 分钟
2025-08-01
安装
安装 axios
npm install axios --save
安装 vue-axios
npm install vue-axios --save
配置
安装 axios
和 vue-axios
后,在 main.js
中引入:
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
如果没有安装 vue-axios
,只安装 axios
也可以使用,但 main.js
中要配置如下:
import axios from "axios";
//下面是将$axios挂在原型上,以便在实例中能用 this.$axios能够拿到
Vue.prototype.$axios = axios;
使用 axios 请求网络
注意
- 如果安装了
vue-axios
,用this.axios.get(url).then().catch();
; - 如果没有安装
vue-axios
、只安装了axios
,用this.$axios.get(url).then().catch()
拿到axios
。
get 请求
this.axios
.get(url)
.then((res) => {
console.log("res.data:", res.data);
})
.catch((err) => {
console.log("err:", err);
});
也可以写成 API 形式:
this.axios({
method: "get",
url: url,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
post 请求
this.axios
.post(url, params)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
也可以写成 API 形式:
this.axios({
method: "post",
url: url,
data: params,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
执行多个并发请求
App.vue
<template>
<div id="app">
<button @click="loginGet()">axios get request</button>
<button @click="loginPost()">axios post request</button>
<button @click="login()">login</button>
</div>
</template>
<script>
export default {
name: "app",
components: {},
methods: {
/**
* 用 vue-axios 调用 axios, get请求
* 安装引入后直接用 this.axios.get().then().catch()
* */
vueaxiosGet(url) {
var that = this;
// 没有安装vue-axios时,用 that.$axios
// return that.axios.get(url).then((res) => {
// console.log("res.data:", res.data);
// }).catch((err) => {
// console.log("err:", err);
// });
return that
.axios({
method: "get",
url: url,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
/**
* 用 vue-axios 调用 axios, post请求
* 安装引入后直接用 this.axios.post().then().catch()
* */
vueaxiosPost(url, params) {
var that = this;
// return that.axios.post(url, params).then((res) => {
// console.log(res.data)
// }).catch((err) => {
// console.log(err)
// });
return that
.axios({
method: "post",
url: url,
data: params,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
loginGet() {
var url = "https://autumnfish.cn/api/joke/list";
var paramName = "num";
var paramNum = 3;
var urll = url + "?" + paramName + "=" + paramNum.toString();
this.vueaxiosGet(urll);
},
loginPost() {
var myurl = "https://autumnfish.cn/api/user/reg";
var params = {
username: "jack",
};
this.vueaxiosPost(myurl, params);
},
login() {
var that = this;
// 先写哪个就先执行哪个
this.axios.all([that.loginGet(), that.loginPost()]).then(
that.axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
console.log("两个请求现在都执行完成");
})
);
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
button {
margin: 5px;
}
</style>
执行结果: