vue前端发起http请求时this错用

js的作用域与this

在发起http请求时容易用错,使用that区分

(在event handler中易用错,类似)

new Vue({
    data:{
        cities:[...]
    },
    methods:{
        my_http_request:function(){
        let that = this
        axios.get('http://...').then(function(response){
    		//这里不能用this赋值
    		that.cities = response.data.result
    		})
    }
                }
})

my_http_request方法向远程发起一个请求,然后把返回的response中的值赋给cities。

在axios.get之前定义一个变量 let that= this .此时,that 和this都处于同一个‘vue’实例中。

但是在 axios,get(...).then(...)函数中,就不能再使用this了,因为在.then(...)中,这是function callback, 其中的this会代表这个http request event。

posted @ 2021-07-22 17:20  Acezhang  阅读(374)  评论(0编辑  收藏  举报