数据交互 axios

在vue中,我们不可能为了网络请求而特意引入jQuery,之前vue里有vue-resource来解决网络请求问题,后来官方建议使用axios,而vue-resource则不再维护。

axios的详细教程见github地址:
https://github.com/axios/axios

安装:
  npm install axios
  或
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用:

  一、配置文件式:

axios(config).then(res=>{to-do}).catch(err=>{to-do})

  以get和post请求说明

        //get:
            axios({
                method:'GET',
                url:'http://www.zhouxiaohouer.com/api/getsth',
                params:{
                    name:'黄焖鸡米饭',
                    price:34
                }
            }).then(res=>{
                console.log(res.data)
            }).catch(err=>{
                console.log(err)
            })

        //post:
            axios({
                method:'POST',
                url:'http://www.zhouxiaohouer.com/api/poststh',
                data:{
                    name:'黄焖鸡米饭',
                    price:34
                },
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded'
                  },
                transformRequest: [function (data, headers) {
                    //转换data数据的数据格式,一般返回一个序列化的字符串
                    //axios内封装了一个qs模块,引入后可以直接转换
                    return data;
                }],
            }).then(res=>{
                console.log(res.data)
            }).catch(err=>{
                console.log(err)
            })   

  二、别名式:

axios.get(url[, config])
axios.post(url[, data[, config]])

  以一个在vue组件里的部分代码说明

            import axios from 'axios'
            import qs from 'qs'

            getGoods(){
              var _this = this
              var data = {
                filter:'-_id -__v',
              }
              axios.post(
                'http://www.zhouxiaohouer.com/api/poststh',
                qs.stringify(data),
                {
                    headers: {
                        'Content-Type':'application/x-www-form-urlencoded'
                    }
                })
                .then(
                    res=>{
                        _this.msg = JSON.stringify(res.data)
                    },
                    err =>{
                        console.log(err)
                    }
                )
            }        

在axios中,我们还可以事先配置默认的全局配置

axios.defaults.baseURL = 'https://www.zhouxiaohouer.com/api'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
原文地址:https://www.cnblogs.com/zhouxiaohouer/p/8028485.html