在微信小程序的前端开发中,使用this.setData方法修改data中的值,其格式为
this.setData({'参数名1': 值1,'参数名2': 值2)}
需要注意的是,如果是简单变量,这里的参数名可以不加引号。
经过测试,可以使用3种方式对data中的对象、数组中的数据进行修改。
假设原数据为:
data: {user_info:{name: 'li',age: 10},cars:['nio', 'bmw', 'wolks']},
方式一:
使用['字符串'],例如
this.setData({['user_info.age']: 20,['cars[0]']: 'tesla'})
方式二:
构造变量,重新赋值,例如
var temp = this.data.user_infotemp.age = 30this.setData({user_info: temp})
var temp = this.data.carstemp[0] = 'volvo'this.setData({cars: temp})
方式三:
直接使用字符串,此种方式之前不可以,现在可以了,估计小程序库升级了。
注意和第一种方法的对比,推荐还是使用第一种方法。
this.setData({'user_info.age': 40,'cars[0]': 'ford'})
完整代码:
Page({/*** 页面的初始数据*/data: {user_info:{name: 'li',age: 10},cars:['nio', 'bmw', 'wolks']},change_data: function(){console.log('对象-修改前:', this.data.user_info)this.setData({['user_info.age']: 20})console.log('对象-修改后1:', this.data.user_info)var temp = this.data.user_infotemp.age = 30this.setData({user_info: temp})console.log('对象-修改后2:', this.data.user_info)this.setData({'user_info.age': 40})console.log('对象-修改后3:', this.data.user_info)console.log('数组-修改前:', this.data.cars)this.setData({['cars[0]']: 'tesla'})console.log('数组-修改后1:', this.data.cars)var temp = this.data.carstemp[0] = 'volvo'this.setData({cars: temp})console.log('数组-修改后2:', this.data.cars)this.setData({'cars[0]': 'ford'})console.log('数组-修改后3:', this.data.cars)}})
效果:
