微信小程序中,this.setData() 失败
- 第一种写法:无效写法(弹窗不能弹起)
data:{
popShows:{ // 弹窗
edu:false, // 选择学历
address:false // 选择现居地
},
},
--------无效写法(弹窗不能正常弹起)---------
// 弹窗(无效写法1)
onShowPop(e){
console.log('e',e)
const {popname} = e.target.dataset
const str = [`popShows.${popname}`] // 这里有变动
this.setData({
str: true
})
},
// 弹窗(无效写法2)
onShowPop(e){
console.log('e',e)
const {popname} = e.target.dataset
const str = `popShows.${popname}` // 这里有变动
this.setData({
str: true
})
},
- 第二种写法:正常写法(弹窗可以正常弹起)
data:{
popShows:{ // 弹窗
edu:false, // 选择学历
address:false // 选择现居地
},
},
----------弹窗可以正常弹起--------------
onShowPop(e){
console.log('e',e)
const {popname} = e.target.dataset
this.setData({
[`popShows.${popname}`]: true
})
},
或者
onShowPop(e){
console.log('e',e)
const {popname} = e.target.dataset
const str = `popShows.${popname}` // 这里有变动
this.setData({
[str]: true
})
},
ES6对象属性表达式
总结
引自 chatGpt :
第一种写法中的 "str" 只是 一个字符串变量,而不是一个对象属性名。而第二种写法使用了 ES6 的计算属性语法,可以动态地生成对象的属性名。因此第二种写法可以正确的设置对象属性的值。