微信小程序实现收藏与取消收藏切换图片功能微信小程序实现收藏与取消收藏切换图片功能
主要介绍了微信小程序实现收藏与取消收藏切换图片功能,非常不错,具有一定的参考借鉴价值,需要的朋友可以
参考下
wxml界面使用image标签
<image wx:if="{{collected}}" catchtap='onCollectionTap' src='/images/icon/collection.png'></image>
<image wx:else src='/images/icon/collection-anti.png' catchtap='onCollectionTap'></image>
js文件上的脚本:
// pages/post_detail/post_detail.js
var postData = require("../../data/posts_data.js")
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
var postId = options.id;
this.data.currentPostId = postId
var postsData = postData.postList[postId];
console.log(postsData);
// this.data.postData=postsData;
this.setData({
post_key: postsData
})
// var postsCollected={
// 1:"true",
// 2:"false",
// 3:"true",
// }
// console.log(postData);
// 从缓存中读取所有的缓存状态
var postsCollected = wx.getStorageSync("posts_Collected")
//如果缓存为真,执行以下代码
if (postsCollected) {
//读取其中一个缓存状态
var postsCollected = postsCollected[postId]
this.setData({
//将是否被收藏的状态上绑定到collected这个变量上
collected: postsCollected
})
} else {
var postsCollected = {};
postsCollected[postId] = false;
wx.setStorageSync("posts_Collected", postsCollected)
}
},
onCollectionTap: function(event) {
//获取缓存的方法
var postsCollected = wx.getStorageSync('posts_Collected');
var postCollected = postsCollected[this.data.currentPostId];
console.log(postCollected);
//取反操作,收藏的话,点击变成未收藏,反之,变成收藏。
postCollected = !postCollected;
postsCollected[this.data.currentPostId] = postCollected;
// //更新文章是否收藏的缓存值。
// wx.setStorageSync('posts_Collected', postsCollected)
// //更新数据绑定变量,从而实现切换图片。
// this.setData({
// collected: postCollected
// })
this.showModal(postsCollected, postCollected)
// wx.showToast({
// title: postCollected ? "收藏成功" : "取消收藏",
// duration: 800,
// icon: "success"
// })
// wx.showModal({
// title: '确定收藏',
// content: '这是一个模态弹窗',
// success: function (res) {
// if (res.confirm) {
// console.log('用户点击确定')
评论0