vue axios基础使用

npm安装

$ npm install axios --save

发送GET请求

 axios.get('api/getData.php',{
            // 还可以直接把参数拼接在url后边
        params:{
     
            data:'参数'
        }
    }).then(function(res){
     
        this.goodsList = res.data;
    }).catch(function (error) {
     
        console.log(error);
    });

发送POST请求

axios.post('/user', {
     
    data: '参数',
}).then(function (response) {
     
    console.log(response);
}).catch(function (error) {
     
    console.log(error);
});

执行多个并发请求

//获得用户信息的请求
function getUserAccount() {
     
     return axios.get('/user/12345');
}
 
//获取用户许可证的请求
function getUserPermissions() {
     
     return axios.get('/user/12345/permissions');
}
 
axios.all( [ getUserAccount(),  getUserPermissions() ] )
    .then(axios.spread(function (acct, perms) {
     
        //两个请求现已完成
    })
);

请求拦截器和响应拦截器

//请求拦截器
axios.interceptors.request.use(
  function (config) {
     
      // 在发送请求之前做些什么
      return config;
  },
  function (error) {
     
      // 对请求错误做些什么
      return Promise.reject(error);
  }
);

//响应拦截器
axios.interceptors.response.use(
  function (config) {
     
      // 对响应数据做点什么
      return config;
  },
  function (error) {
     
      // 对响应错误做点什么
      return Promise.reject(error);
  }
);

Vue中axios在发送POST请求时,参数的处理

  1. 下载安装第三方模块 qs -> npm install qs --save-dev
  2. 处理方式
// 第一种: 直接在发送的时候,对数据进行qs.stringify处理
// 缺点: 如果项目大,有大量的请求需要发送,那么一个一个加会很麻烦
axios.post("/checkLogin.php", qs.stringify({
     
  name, pwd
}));

// 第二种: 使用axios.create创建一个新的axios实例,统一对数据进行处理, 同时也要借助qs模块
const Axios = axios.create({
     
  baseURL: '/api',
  transformRequest: [function (data) {
     
    const d = qs.stringify(data)
    return d;
  }]
})

Axios.post("/checkLogin.php", {
     
  name, pwd
});

你可能感兴趣的:(vue)