小程序中data数据的处理方法总结
wxml代码:
1 <view class="container"> 2 <view wx:for="{{list}}" wx:key="this" style="padding: 10px 0;border-bottom: 1px solid #ddd;"> 3 <view> 4 {{index+1}}、{{item.name}} 5 </view> 6 <view class="textright font12" style="color: #2A53CD;"> 7 <text bindtap="remove" data-index="{{index}}" class="marlr10">删除</text> 8 <text bindtap="edit" data-index="{{index}}" >修改</text> 9 </view> 10 </view> 11 <button class="martop20" bindtap="add_before"> 12 向前插入数组 13 </button> 14 <button class="martop20" bindtap="add_after"> 15 向后插入数组 16 </button> 17 <button class="martop20" bindtap="clear"> 18 清空数组 19 </button> 20 </view>
js代码:
1 //index.js 2 //获取应用实例 3 var app = getApp() 4 Page({ 5 data: { 6 list:[{ 7 id:1, 8 name:'应季鲜果', 9 count:1 10 },{ 11 id:2, 12 name:'精致糕点', 13 count:6 14 },{ 15 id:3, 16 name:'全球美食烘培原料', 17 count:12 18 },{ 19 id:4, 20 name:'无辣不欢生猛海鲜', 21 count:5 22 }] 23 }, 24 //向前增加数据 25 add_before:function (){ 26 //要增加的数组 27 var newarray = [{ 28 id:6, 29 name:'向前增加数据--'+new Date().getTime() , 30 count:89 31 }]; 32 this.data.list = newarray.concat(this.data.list); 33 this.setData({ 34 'list': this.data.list 35 }); 36 }, 37 //向后增加数据 38 add_after:function (){ 39 40 //要增加的数组 41 var newarray = [{ 42 id:5, 43 name:'向后增加数据--'+new Date().getTime() , 44 count:89 45 }]; 46 this.setData({ 47 'list':this.data.list.concat(newarray) 48 }); 49 }, 50 //删除 51 remove:function (e){ 52 53 var dataset = e.target.dataset; 54 var Index = dataset.index; //拿到是第几个数组 55 56 this.data.list.splice(Index,1); 57 58 this.setData({ 59 list:this.data.list 60 }); 61 }, 62 //修改 63 edit:function (e){ 64 var dataset = e.target.dataset; 65 var Index = dataset.index; //拿到是第几个数组 66 this.data.list[Index].name = '修改了内容'+new Date().getTime(); 67 68 this.setData({ 69 list:this.data.list 70 }); 71 }, 72 //清空 73 clear:function (){ 74 75 this.setData({ 76 list:[] 77 }); 78 } 79 80 })
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; }
效果图如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通