# npm 安装
1、安装 axios
npm install axios --save
- axios不能直接使用Vue.use()方法,需要导入专门的一个包来整合使用axios,使用npm安装‘vue-axios’包并将其添加进项目依赖
2、安装 vue-axios
npm install vue-axios --save
3、安装 qs
npm install qs
- qs 的作用就是将对象序列化,多个对象之间用&拼接(拼接是由底层处理,无需手动操作)
- 使用qs只需要在要使用qs的组件里引入,然后直接使用它的方法即可
# 在 main.js 中写入以下内容:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);
注意:在项目的组件中使用axios时在前面要加上this.关键字,表明是vue自身提供的方法,而不是自己创建的方法。
# axios 使用
1、执行 GET 不带参请求
methods: {
get() {
this.axios
.get('https://www.apiopen.top/weatherApi')
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}
2、执行 GET 带参请求
methods: {
get() {
this.axios
.get('https://www.apiopen.top/weatherApi', {
params: {
city: '阳江'
}
})
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}
3、执行 POST 请求
import qs from 'qs' // 引入qs
methods: {
post() {
let postData = qs.stringify({
id: 'id'
});
this.axios
.post('url', postData)
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}