uniapp 微信小程序调用微信云开发服务器返回的数据如何赋值给data 变量?
data(){
return{
rentlists="13123"
}
}
created(){
const db = wx.cloud.database()
db.collection('myRent').where({
type: 'info'
}).get({
success: function(res) {
let that=this
console.log(that.rentlists); // undefined? 预期应该是rentlists="13123"
// 输出 [{ "title": "The Catcher in the Rye", ... }]
that.rentlists=res.data; //能接收到数据、
console.log(that.rentlists) //此时res.data的确赋值给rentlists 但这个rentlists似乎不是上方data中的rentlists?
}
})
},
该回答引用ChatGPT
在您的代码中,可以通过 that 变量来访问 Vue 实例中的 data 变量,但是 that 变量在 success 函数内部定义,而 this 关键字的作用域在 success 函数内部也是不同的,这导致了 that.rentlists 和 this.rentlists 引用的是不同的变量。
为了在 success 函数中访问 Vue 实例的 data 变量,可以先将 Vue 实例的 this 绑定到另一个变量,然后在 success 函数中通过这个变量来访问 data 变量。可以按照如下方式修改代码:
data() {
return {
rentlists: "13123"
};
},
created() {
const db = wx.cloud.database();
let vm = this;
db.collection('myRent').where({
type: 'info'
}).get({
success: function (res) {
console.log(vm.rentlists); // vm 变量引用的是 Vue 实例,可以通过它来访问 data 变量
vm.rentlists = res.data;
console.log(vm.rentlists);
}
})
}
在上述代码中,我使用了 vm 变量来引用 Vue 实例,在 success 函数内部通过这个变量来访问 data 变量。