比如page的data里有一个message,想要在执行wx.request成功的时候修改它的值
data: {message:"hi~"}
一般很容易这样写:
wx.request({url: 'https://www.some.com/user',method:'POST',data: {code: res.code},header: {'content-type': 'application/json' },success: function (res) {console.log(res.data);this.setData({ message: 'success' }); //错误的写法 }
})
上面 this.setData中的this对象已经不是page了。修改一下,正确的代码:
var that = this; //把page对象赋值给新建的对象wx.request({url: 'https://www.some.com/user',method:'POST',data: {code: res.code},header: {'content-type': 'application/json' },success: function (res) {console.log(res.data);that.setData({ message: 'success' }); //这里用that}
})
转载自:https://www.jianshu.com/p/95994e5d2e19