小程序中data數據的處理方法總結(小程序交流羣:604788754)

WXML:html

<view class="container">
<view wx:for="{{list}}" wx:key="this" style="padding: 10px 0;border-bottom: 1px solid #ddd;">
	<view>
		{{index+1}}、{{item.name}}
	</view>
	<view class="textright font12" style="color: #2A53CD;">
		 <text bindtap="remove" data-index="{{index}}" class="marlr10">刪除</text>	
		 <text bindtap="edit" data-index="{{index}}" >修改</text>	
	</view>
</view>
<button class="martop20" bindtap="add_before">
	向前插入數組
</button>
<button class="martop20" bindtap="add_after">
	向後插入數組
</button>
<button class="martop20" bindtap="clear">
	清空數組
</button>
</view>

 WXSS:數組

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}

JS:app

//index.js
//獲取應用實例
var app = getApp()
Page({
  data: {
        list:[{
                id:1,
                name:'應季鮮果',
                count:1
        },{
                id:2,
                name:'精緻糕點',
                count:6
        },{
                id:3,
                name:'全球美食烘培原料',
                count:12
        },{
                id:4,
                name:'無辣不歡生猛海鮮',
                count:5
        }]
  },
  //向前增長數據
  add_before:function (){
      //要增長的數組
      var newarray = [{
              id:6,
              name:'向前增長數據--'+new Date().getTime() ,
              count:89
      }];
        this.data.list = newarray.concat(this.data.list);
      this.setData({
          'list':    this.data.list
      });
  },
  //向後增長數據
  add_after:function (){

          //要增長的數組
      var newarray = [{
              id:5,
              name:'向後增長數據--'+new Date().getTime() ,
              count:89
      }];
      this.setData({
          'list':this.data.list.concat(newarray)
      });
  },
  //刪除
  remove:function (e){
      
      var dataset = e.target.dataset;
      var Index = dataset.index; //拿到是第幾個數組
      
      this.data.list.splice(Index,1);
      
      this.setData({
          list:this.data.list
      });
  },
  //修改
  edit:function (e){
      var dataset = e.target.dataset;
      var Index = dataset.index; //拿到是第幾個數組
      this.data.list[Index].name = '修改了內容'+new Date().getTime();
      
      this.setData({
          list:this.data.list
      });
  },
  //清空
  clear:function (){
      
      this.setData({
          list:[]
      });
  }
  
})

 效果圖以下:xss

相關文章
相關標籤/搜索