vue-cli 里axios的使用

1、axios的安装

cnpm i axios --save
2、axios的引入
安装其他插件的时候,可以直接在 main.js 中引入并 Vue.use(),但是 axios 并不能 use,只能每个需要发送请求的组件中即时引入
为了解决这个问题,那么就可以使用在原型链上挂载的方法传入到各个组件具体方法如下(在vue-cli里面的static里的文件是可以通过网址来访问的,而其他的文件是不能够被访问的)
//首先在main.js中引入
import axios from 'axios'
//这时在其他组件中是无法使用的,要么在各个组件中引入axios,要么就在原型链上挂载这个方法
Vue.prototype.$http= axios

3、axios的配置与使用

通过原型链上挂载的方法,那么就可以在各个组件中使用了

methods: {
    getData() {
        this.$http.get('/app/v1/get-json').then(this.getDataList).catch(this.error);
    },
    getDataList(res) {
        console.log(res);
    },
    error(err) {
        console.log(err);
    }
},
mounted() {
    this.getData();
}

通用axios的配置

//get请求
axios.get('app/v1/get-data', {
           first:'this is first'
           second:'this is second' 
       }
})
//post请求
axios.post('app/v1/get-data', {
           first:'this is first'
           second:'this is second' 
       }
})
//也可以进行配置来发送请求
//发送一个`POST`请求,注意this的指向问题,可以用箭头函数,也可以用bind(this)来更正this的指向问题
axios({
    method:"POST",
    url:'/app/v1/get-data',
    data:{
      name:"virus" 
    }
}).then(function(res){}.bind(this)).catch(function(err){})

 axios利用ES6技术可以实现多个请求同时发送接收

function getUserAccount(){
  return axios.get('/app/v1/get-data');
}
function getUserPermissions(){
  return axios.get('/app/v1/get-json');
}
axios.all([getUserAccount(),getUserPermissions()])
  .then(axios.spread(function(acct,perms){
    //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
  }))

 axios 已经支持了各种请求方式

axios.request(config);

axios.get(url[,config]);

axios.delete(url[,config]);

axios.head(url[,config]);

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

axios.put(url[,data[,config]])

axios.patch(url[,data[,config]])

4、配置本地的请求地址来适配线上环境,避免线上线下请求地址的频繁更改

methods: {
    getData() {
        // 本地需要访问的是的地址是‘/static/data/index.json’,但是线上的地址是'/app/v1/get-json'这个时候就需要配置一下地址了
        axios.get('/app/v1/get-json').then(this.getDataList).catch(this.error);
    },
    getDataList(res) {
        console.log(res);
    },
    error(err) {
        console.log(err);
    }
},
mounted() {
    this.getData();
}

如何配置

  a、打开项目下的config->index.js的文件

  b、在dev下面的proxyTable配置项中进行配置具体如下

proxyTable: {
    '/app': {
        //线下的URL地址
        target: 'http://localhost:8080',
        pathRewrite: {
            //当访问线上地址的的时候,会默认适配到对应的线下地址
            '^/app/v1/get-data': '/static/data/index.json',
            '^/app/v1/get-json': '/static/data/index.json'
        }
    }
},    

 

转载于:https://www.cnblogs.com/rickyctbu/p/9834061.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值