uniapp 使用this指针无法修改data变量的问题
原代码:
Sex() { console.log(this); uni.showActionSheet({ title:"选择性别", itemList: ['男','女'], itemColor: "#55aaff", success(res) { const n=res.tapIndex+1; switch(n) { case 1: this.Sex_Text='男' break; case 2: this.Sex_Text='女' break; } } }) },
原因:在success函数中使用了箭头函数(() => {})。箭头函数不会绑定this指向,所以在箭头函数中无法访问组件实例的this。
解决办法:使用function关键字定义匿名函数来替代箭头函数。
修改后的代码:
Sex() { uni.showActionSheet({ title: "选择性别", itemList: ['男', '女'], itemColor: "#55aaff", success: function(res) { // 使用 function 关键字来定义函数 const n = res.tapIndex + 1; switch (n) { case 1: this.Sex_Text = '男'; break; case 2: this.Sex_Text = '女'; break; } }.bind(this) // 使用 bind(this) 来绑定函数作用域 }) },
这样变量就能修改了。