问题

在之前的 VUE 使用一个定义了的属性,一直用的是 this.xxx,而在 uni-app 中使用 this.xxx,却发现无法赋值的问题

uni.login({
	provider: 'weixin',
	success: function (loginRes) {
		this.code = loginRes.code
	}
})

为什么会出现这样的问题呢?是因为在 function 中的 this 指向的是 login 这个方法。

解决

既然是因为 this 作用域的问题,就要使 this 指向外面的作用域,常见的有两种解决方法:

  • 在外层赋值给另一个变量使用
    let _this = this;
    uni.login({
    	provider: 'weixin',
    	success: function (loginRes) {
    		_this.code = loginRes.code
    	}
    })
    
  • 使用箭头函数
    uni.login({
    	provider: 'weixin',
    	success: (loginRes) => {
    		this.code = loginRes.code
    	}
    })
    

    为什么箭头函数可以呢?是因为 ES6 语法中,箭头函数的 this 指向的是父函数的 this

Logo

前往低代码交流专区

更多推荐