微信小程序动态点赞php,在微信小程序中如何实现点赞功能
這篇文章主要介紹了微信小程序基于本地緩存實現(xiàn)點贊功能的方法,涉及微信小程序界面布局、事件響應及緩存操作等相關實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了微信小程序基于本地緩存實現(xiàn)點贊功能的方法。分享給大家供大家參考,具體如下:
wxml中的寫法
注意:
1. 使用wx:if="{{condition}}" wx:else實現(xiàn)圖標的切換效果;
2. 為圖片綁定點擊事件bindtap="toCollect",兩個image標簽都要綁定!
js中的寫法:Page({
data: {
},
onLoad: function(option) {
// 獲取接收到的id值
var getId = option.id;
// 讓接收到的id值傳遞到data:{}里面
this.setData({
currentId: getId
});
// 讀取所有的文章列表點贊緩存狀態(tài)
var cache = wx.getStorageSync('cache_key');
// 如果緩存狀態(tài)存在
if (cache) {
// 拿到所有緩存狀態(tài)中的1個
var currentCache = cache[getId];
// 把拿到的緩存狀態(tài)中的1個賦值給data中的collection,如果當前文章沒有緩存狀態(tài),currentCache 的值就是 false,如果當前文章的緩存存在,那么 currentCache 就是有值的,有值的說明 currentCache 的值是 true
this.setData({
collection: currentCache
})
} else {
// 如果所有的緩存狀態(tài)都不存在 就讓不存在的緩存存在
var cache = {};
// 既然所有的緩存都不存在,那么當前這個文章點贊的緩存也不存在,我們可以把當前這個文章點贊的緩存值設置為 false
cache[getId] = false;
// 把設置的當前文章點贊放在整體的緩存中
wx.setStorageSync('cache_key',cache);
}
},
// 點擊圖片的點贊事件 這里使用的是同步的方式
toCollect: function(event) {
// 獲取所有的緩存
var cache = wx.getStorageSync('cache_key');
// 獲取當前文章是否被點贊的緩存
var currentCache = cache[this.data.currentId];
// 取反,點贊的變成未點贊 未點贊的變成點贊
currentCache = !currentCache;
// 更新cache中的對應的1個的緩存值,使其等于當前取反的緩存值
cache[this.data.currentId] = currentCache;
// 重新設置緩存
wx.setStorageSync('cache_key',cache);
// 更新數(shù)據綁定,從而切換圖片
this.setData({
// collection 默認的是 false
collection: currentCache
});
// 交互反饋
wx.showToast({
title: currentCache?'點贊':'取消',
icon: 'success',
duration: 2000
});
}
})
js中操作反饋—wx.showModal的寫法:// 點擊圖片的點贊事件 這里使用的是同步的方式
toCollect: function(event) {
// 獲取緩存,得到當前文章是否被點贊
var cache = wx.getStorageSync('cache_key');
// 獲取當前文章是否被點贊的緩存
var currentCache = cache[this.data.currentId];
// 取反,點贊的變成未點贊 未點贊的變成點贊
currentCache = !currentCache;
// 更新cache中的對應的1個的緩存值,使其等于當前取反的緩存值
cache[this.data.currentId] = currentCache;
// 調用 showModal方法
this.showModal(cache,currentCache);
},
showModal: function(cache,currentCache) {
var that = this;
wx.showModal({
title: "點贊"
content: currentCache?"要點贊嗎?":"要取消贊嗎?",
showCancel: "true",
cancelText: "取消",
cancelColor: "#666",
confirmText: "確定",
confirmColor: "#222",
success: function(res) {
if (res.confirm) {
// 重新設置緩存
wx.setStorageSync('cache_key',cache);
// 更新數(shù)據綁定,從而切換圖片
that.setData({
collection: currentCache
})
}
}
})
}
上面是我整理給大家的,希望今后會對大家有幫助。
相關文章:
總結
以上是生活随笔為你收集整理的微信小程序动态点赞php,在微信小程序中如何实现点赞功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux驱动头文件查找目录,在Fedo
- 下一篇: linux make教程,Linux下m