axios使用:底层还是原生js实现,内部通过promise封装一种前端异步请求后端的技术
axios原理:浏览器window接口的XMLHttpRequest
axios:基于原生ajax + promise技术封装通用于前后端的请求库
1.下载axios在main.js中引入
yarn add axios //下载
import axios from 'axios' //引入
2.在main.js中配置基础地址
axios.defaults.baseURL = 'https://www......'
3.将axios挂载到vue的原形上作为全局属性
Vue.prototype.$axios = axios
4.在methods中写入axios的发送请求
async getGoodsList() {
const { data } = await this.$axios({
url: "接口地址",
// 默认为get请求,可以省略method
});
this.list = data.data;
console.log(this.list);
},
5.在created中调用请求函数
created() {
this.getGoodsList();
},
GET:axios的params项会把参数自动写到url后面
POST:axios的data选项会把参数自动装入到请求体中
最后发给后台的请求体数据格式是:JSON字符串格式