有时我们需要微信小程序的收藏功能,具体实现如下:
/* 收藏 */ var postsCollected = wx.getStorageSync('posts_Collected') if (postsCollected) { var postCollected = postsCollected[postId] this.setData({ collected: postCollected }) } else { var postsCollected = {} postsCollected[postId] = false; wx.setStorageSync('posts_Collected', postsCollected); } onColletionTap:function (event) { var postsCollected = wx.getStorageSync('posts_Collected'); var postCollected = postsCollected[this.data.currentPostId]; //收藏变成未收藏,未收藏变成收藏 postCollected = !postCollected; postsCollected[this.data.currentPostId] = postCollected; //更新文章是否的缓存值 wx.setStorageSync('posts_Collected', postsCollected); //更新数据绑定变量,从而实现切换图片 this.setData({ collected: postCollected }) }