Vue中如何在回调函数中访问组件本地变量?
解决Vue回调中
this指向问题(不修改handleResponse结构) 你遇到的这个错误确实是因为回调函数里的this没有指向Vue组件实例——普通函数作为回调时,this的指向会绑定到调用它的上下文(这里是then内部的上下文),而不是你的组件。好在不用改handleResponse的结构,有几种简单的办法能解决:
方法1:提前保存this的引用
在created钩子开头,把组件的this存到一个变量里,比如that或者self,然后在回调里用这个变量访问组件数据:
created: function() { var params = {'id': this.$route.params.stockId} // 保存组件的this引用 const that = this fetchStock( params, function(response) { // 用that代替this访问组件实例 that.stock = response.data.payload console.log(response) }, function(responseError) { console.log(responseError) } ) }
方法2:使用箭头函数(推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this,刚好符合我们的需求,把两个回调都改成箭头函数就行:
created: function() { var params = {'id': this.$route.params.stockId} fetchStock( params, (response) => { // 这里的this就是组件实例 this.stock = response.data.payload console.log(response) }, (responseError) => { console.log(responseError) } ) }
方法3:用bind绑定this
如果坚持要用普通函数,可以用bind把回调函数的this绑定到组件实例:
created: function() { var params = {'id': this.$route.params.stockId} fetchStock( params, function(response) { this.stock = response.data.payload console.log(response) }.bind(this), function(responseError) { console.log(responseError) }.bind(this) ) }
这三种方法都不需要修改handleResponse的结构,其中箭头函数是最简洁直观的方案,也是Vue项目里常用的写法。
内容的提问来源于stack exchange,提问作者den0
相关产品推荐
相关产品推荐

