微信小程序怎样用setData修改字典和在数组中添加

setData函数在小程序中具有同时修改前端和后端的功能,应该是进行数据修改中最常用的一个功能了。

修改data中的变量

wxml

<view>
  {{information}}
</view>
<view>
  <button type="primary" bindtap="click">修改信息</button>
</view>

js

// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    information:"你好!"
  },
  click(){
    this.setData({information:"hello world!"})
  },
})

前后端一起进行修改。
效果

修改字典

wxml

<view>
  {{information.name}}
  {{information.age}}
</view>
<view>
  <button type="primary" bindtap="click">修改信息</button>
</view>

js

Page({
  data: {
    information:{
      name:"张三",
      age:120
    }
  },
  click(){
    this.setData({'information.name':'李四'})//需要将字典和键用引号引起来
  },
})

修改数组

<view wx:for="{{informations}}" wx:key="key">
  {{item.name}}
  {{item.age}}
</view>
<view>
  <button type="primary" bindtap="click">修改信息</button>
</view>

js

Page({
  data: {
    informations:[
      {
      name:"张三",
      age:100
      },
      {
        name:"李四",
        age:120
      },
  ]
  },
  click(){
    this.setData({'informations[1].name':'王五'})
    this.setData({'informations[1].age':92})
  },
})

向数组中添加元素.

wxml

<view wx:for="{{informations}}" wx:key="key">
  {{item.name}}
  {{item.age}}
</view>
<view>
  <button type="primary" bindtap="click">修改信息</button>
</view>

js

Page({
  data: {
    informations:[
      {
      name:"张三",
      age:100
      },
      {
        name:"李四",
        age:120
      }
      
  ]
  },
  click(){ 
    var informations = this.data.informations//必须在暂存一下不然报错(说this.data.informations没有push方法,我也懵了)
    informations.push({name:"王五", age:"92"})
    this.setData({informations: informations})
  }
})

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值