axios特点

场景

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。在进行Vue实验时,需要用到axios进行接口请求,并将返回的内容传递到Vue的data选项中。正常情况下,会使用this.list = response.data的格式进行赋值,但this的指向恰恰是最容易被忽略的地方。

其特点如下:
1.从浏览器中哦=创建XMLHttpRequest
2.从node.js中发出http请求
3.支持Promise API
4.拦截请求和响应
5.转换请求和响应数据
6.取消请求
7.自动转换JSON数据
8.客户端支持防止CSRF/XSRF

解决axios 中this 指向问题

1.使用箭头函数来解决

示例:

methods:{
    loginAction(formName){
        this.$axios.post('http://124.0.0.1/u.subLogin',{
            username:this.username,
            password:this.password,
        }).then((response)=>{
            console.log(this.list);
           //this.list =response.data
        }).catch((err)=>{
            console.log(this);
        })
    }
}

2.使用.bind(this)在回调函数后面解决

示例:

getRequest:function(){
    axios.get('http:/124.0.0.1/u/subBOf',{
        username:this.username,
        password:this.password
    }).then(function(resp){
        console.log(this.list)
    //this.list = resp.data
    }).bind(this)
    .catch(function(err){
        console.log(err)
    })
}

3.使用that传递this变量

示例:

getRequest:function(){
    var that =this;
    axios.get('http:/124.0.0.1/s/shus',{
        username:this.username,
        passoword:this.password
    }).then(function(resq){
        console.log(that.list)
    //that.list = resq.data
    }).catch(function(err){
        console.log(err)
    })
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐