回顾
微信小程序数据操作上:合理组装数据主要准备一些在操作一个基本的数据使用。
本文
本文讲以几个实际场景来介绍一下我在微信小程序中如何处理数据的深度操作
场景1:微信小程序中的深度Clone
- 场景:复杂对象下的Clone和修改
比如在wxParse 0.3 微信小程序HTML及markdown富文本解析自定义组件 中,涉及到元素很复杂。我们如何处理节点的修改以及遍历
{
"node": "article",
"nodes": [
{
"node": "text",
"text": " ",
"textArray": [
{
"node": "text",
"text": " "
}
]
},
{
"node": "element",
"tag": "div",
"tagType": "block",
"styleStr": "text-align:center;margin-top:10px;",
"attr": {
"style": "text-align:center;margin-top:10px;"
},
"nodes": [
{
"node": "text",
"text": "\t\t",
"textArray": [
{
"node": "text",
"text": "\t\t"
}
]
},
{
"node": "element",
"tag": "img",
"tagType": "inline",
"attr": {
"src": "https://weappdev.com/uploads/default/original/1X/84512e0f4591bcf0dee42c3293f826e0c24b560c.jpg",
"alt": "wxParse-微信小程序富文本解析组件Logo"
},
"imgIndex": 0,
"from": "article"
},
{
"node": "text",
"text": "\t\t\t",
"textArray": [
{
"node": "text",
"text": "\t\t\t"
}
]
},
......
为什么不用Object.assign()?
详见:Object.assign()
如果你在使用es6,那么或许你正在使用Object.assign()
,但是注意Object.assign()
在Android上是不被支持的。-
解决: 使用深度Clone工具类
function clone(obj) { var o; if (typeof obj == "object") { if (obj === null) { o = null; } else { if (obj instanceof Array) { o = []; for (var i = 0, len = obj.length; i < len; i++) { o.push(clone(obj[i])); } } else { o = {}; for (var j in obj) { o[j] = clone(obj[j]); } } } } else { o = obj; } // 在这里可以判断进行处理 if (typeof (o) != 'undefined' && o.node && o.tag === 'img') { } return o; }
场景2:循环中的单值修改
场景: 循环数据展示并修改
如有一个文章列表,你可以点击每列的按钮“收藏”,点击后,更改按钮字"已收藏"-
具体场景代码
//数据 listArray:[ { title:"文章标题1", like:1 }, { title:"文章标题2", like:0 }, { title:"文章标题3", like:0 }, ]
-
处理方式
-
1.在view中绑定索引值index
// 修改View {{listArray}}"> item.title //修改添加data-idx="{{index}}" {{index}}" bindtap="liketap" wx:if="{{item.like == 1}}">已收藏 {{index}}" bindtap="liketap" wx:else>收藏
-
2.方法中进行处理
liketap:function(e){ // 获取索引值 var idx = e.currentTarget.dataset.idx; var that = this; //获取数据 var temArray = this.data.listArray; //修改数据 temArray[idx].like = !temArray[idx].like; // 绑定数据 that.setData({ listArray: temArray; }); }
-
更多场景处理(等待补充)
...