最近这段时间在写微信小程序,有一个页面需要动态修改 data 中的数据,而这里似乎是个坑。
1、正常修改
正常修改很简单,当触发 change 事件时,数据和页面都会同时发生改变。这个也不用多说,很简单的例子。
![](https://upload-images.jianshu.io/upload_images/17756753-c4002576e6ff0f98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/496/format/webp)
2、如何修改对象中某个属性值
当你想把下面代码中 human 中的 height 的值改成 178 时,直接用 this.setData ({human.height: 178}) 会报错。
![](https://upload-images.jianshu.io/upload_images/17756753-f8a7c7a94c856c8f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/661/format/webp)
这个时候可以先用字符串拼接属性名,然后用 [] 包裹起来,这里画上,待会可能要考。
![](https://upload-images.jianshu.io/upload_images/17756753-bac23983e5e4a974.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/673/format/webp)
3、如何动态修改数组中某个值
动态修改 list [index].height 的值,和上面的例子差不多。
![](https://upload-images.jianshu.io/upload_images/17756753-d29ba35da6ef90d0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/673/format/webp)
先用字符串拼接,然后再更改,其中 index 是动态获取的数字。
![](https://upload-images.jianshu.io/upload_images/17756753-7538b58bee46fb18.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/674/format/webp)
4、 那个...
其实好像挺简单,果然还是我太菜,菜是原罪...
首发公众号「我是玖柒后」,在路上,一起成长!