axios使用箭头函数代替_this

方法里用this和方法里的方法里用this,指向的内容不一样

不使用箭头函数

    created(){
        let _this=this;
        axios.get('http://localhost:8081/findAll')
            .then(function(response) {
                _this.users = response.data;
                console.log(_this.users);
            }).catch(function (error) {
            console.log(error);
        })
    }

可以用箭头函数代替_this。

箭头函数错误用法

    created:()=>{
        axios.get('http://localhost:8081/findAll')
            .then( function(response) {
                this.users = response.data;
            }).catch(function (error) {
            console.log(error);
        })
    }

箭头函数正确用法

    created(){
        axios.get('http://localhost:8081/findAll')
            .then( (response)=> {
                this.users = response.data;
            }).catch(function (error) {
            console.log(error);
        })
    }
posted @ 2020-12-01 23:39  xsyz  阅读(936)  评论(0编辑  收藏  举报