Vue 2 + Axios:请求回调修改数据无法控制v-show显示的问题
问题分析与解决方案
核心原因
在Axios的then回调中使用普通函数时,this的上下文会发生改变,不再指向Vue实例,导致无法正确修改isCaptchaError的值。而按钮点击事件中的this始终指向Vue实例,因此能正常生效。
解决方案
方案1:使用箭头函数(推荐)
箭头函数会继承外层作用域的this,确保回调内的this指向Vue实例:
watch: { phoneNumber(val) { axios({ method: 'post', url: '/rest/client', data: ajaxRequest }).then(response => { this.isCaptchaError = true; }) } }
方案2:提前保存Vue实例的引用
在Axios调用前将this赋值给一个变量,回调中使用该变量访问Vue实例:
watch: { phoneNumber(val) { const vm = this; axios({ method: 'post', url: '/rest/client', data: ajaxRequest }).then(function(response) { vm.isCaptchaError = true; }) } }
方案3:绑定回调函数的上下文
使用bind(this)将回调函数的this绑定到Vue实例:
watch: { phoneNumber(val) { axios({ method: 'post', url: '/rest/client', data: ajaxRequest }).then(function(response) { this.isCaptchaError = true; }.bind(this)) } }
内容的提问来源于stack exchange,提问作者Alex Zhulin
相关产品推荐
相关产品推荐

