axios跨域,及axios中this指向

安装 

npm install axios --save-dev

  •  axios 不能直接在 main.js 中引入并 Vue.use(),只能每个需要发送请求的组件中即时引入。
  • 两种解决思路:一 修改原型链,二 axios+vuex 进行封装

一.  main.js 中引入 axios 并且修改原型链:

import axios from 'axios'
​
Vue.prototype.$axios= axios

修改完成,axios的使用详情请参考Axios 中文说明

二.  axios+vuex 进行封装:

  1. vuex:一个专为 Vue.js 应用程序开发的状态管理模式。也可以理解为一种开发模式或框架。
  2. 使用:在main.js引入store,注入。新建一个目录store,….. export 。
  3. 场景:单页应用中,组件之间的状态。音乐播放、登录状态、加入购物车。
  4. 属性:五种,分别是 State、 Getter、Mutation 、Action、 Module。

懒得写了,算了吧,,,,

 


 

vue cli脚手架接口跨域问题,打开config/index.js 进行如下配置

//配置axios跨域
    proxyTable: {
    	'/api': {
        target: 'http://resource.onetuu.com/',//设置你调用的接口域名和端口号
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
        }
      }  
    },

在相关组件中调用

this.$axios({
        method: 'get',
        url: '/api/userInfo',   
         //这里的api为http://http://121.41.130.58:9090/ 指向http://localhost:8081
         //在本地调试时没有问题 但打包发布时,删除/api/
   	}).then((response) => {
          // this.answer = response.data.data;  
           console.log(response.data)
    }).catch(function(err){
         
    })

 


提出一个小问题,在使用axios得到请求结果后,在then的处理函数中,你需要使用箭头函数才能正确使用this。

原本写法,这种情况下,输出this得到的’undefined’

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

修改,利用箭头函数的作用域,由上下文确定(也就是由外层调用者vue来确定)。this将指向Vue对象

axios.get('/user?ID=12345')
  .then((response)=>{
    console.log(response)
  })
  .catch(function (error) {
    console.log(error);
  });

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值