vue项目中使用axios请求网络
参考网址:
[1]https://www.freesion.com/article/7191968296/
[2] http://www.axios-js.com/zh-cn/docs/
[3] https://github.com/axios/axios/blob/master/README.md
一、安装
1.1 安装 axios
npm install axios --save
1.2 安装 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。
3.1 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) });
3.2 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) });
3.3 执行多个并发请求:
App.vue
执行结果: