數據交互 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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM