關(guān)于微信小程序this.setData()用法

基本使用

字符串 數(shù)值 布爾

data: {
    name: 'Blake'
}

this.setData({'name': 'Yang'})

對象

data: {
    person: {
        name: 'Blake',
        age: 9
    }
}

this.setData({'person.name': 'Blake})

高能

普通的數(shù)組

怎樣動(dòng)態(tài)修改某個(gè)元素

//wxss
<view wx:for="{{arr}}" bindtap="changeNum" data-id="index">{{item}}</view>
//js
data: {
    arr: [1,2,3,4,5,6]
}

changeNum(e){
    var id = e.currentTarget.dataset.id
    var str = "arr["+id+"]"
    this.setData({
        [str]: 99
    })
}

or

changeNum(e){
  var id = e.currentTarget.dataset.id
  this.data.arr[id] = 99
  this.setData({
      arr: this.data.arr
   })
}

元素是對象的數(shù)組

當(dāng)元素被點(diǎn)擊時(shí),修改age

//js
data: {
    people: [
        {
            name: 'Blake',
            age: 9
        },
        {
            name: 'Blake',
            age: 9
        },
        {
            name: 'Blake',
            age: 9
        }
    ]
}

changeNum(e){
    var id = e.currentTarget.dataset.id
    var str = "arr["+id+"].age"
    this.setData({
        [str]: 99
    })
}

or

changeNum(e){
  var id = e.currentTarget.dataset.id
  this.data.arr[id].age = 99
  this.setData({
      arr: this.data.arr
   })
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容