动态生成详细页面,缓存切换图片

点击post.wxml中用<block wx:for>生成的模块,跳出相应的详细页面:

1.post.wxml中:

< view catchtap = 'onPostTap' data-postid = "{{item.postId}}">
自定义属性获取data.js中的postId属性

data-postid中的“i”不要大写,因为大写是去掉连字符自动变成大写,如果这时候大写会找不到

2.post.js中 

onPostTap: function(event){
var postId =event.currentTarget.dataset. postid ;
wx.navigateTo({ url: "post-detail/post-detail?id=" + postId })
}

3.在post项目中创建post-detail项目,写出post-detail.wxml模版,在app.json中引入

4.在post-detail.js中引入data.js

var postsData = require ( "../../../data/data.js" )

5.在post-detail.js中onLoad函数中绑定数据

onLoad: function (options) {
var postId =options. id ;
this.setData({
postData : postsData .postList[ postId ]
})
}

postList是data.js中绑定的名字

扫描二维码关注公众号,回复: 3216724 查看本文章

6.在post-detail.wxml文件中,绑定数据前加{{ postData.url}}

利用缓存切换图片

1.设置两个image标签,用wx:if 来切换

< image wx:if= "{{collected}}" src= "/images/collected.jpg" catchtap= 'onCollectedTap'></ image >
< image wx:else src= "/images/no-collected.jpg" catchtap= 'onCollectedTap'></ image >

2.在post-detail.js文件中onLoad读取缓存

var postsCollected = wx.getStorageSync( "posts_collected");

3.判断缓存是否存在:如果存在,获取当前所点击的数据,再进行数据绑定

if (postsCollected){
var postCollected = postsCollected[postId];
this.setData({
collected: postCollected
})
}
4.如果缓存不存在,设置缓存:先创建空的postsCollected,缓存不存在意味着没有收藏过,所以设置当前的数据为false

else{
var postsCollected={};
postsCollected[postId]= false;
wx.setStorageSync( "posts_collected", postsCollected);
}

5.点击函数:先获取缓存,因为onLoad中已经判断过是否有缓存,没有缓存已经设置过了。再获取当前点击的数据。

onCollectedTap: function(event){
var postsCollected = wx.getStorageSync( "posts_collected");
在onLoad中:
this.data.currentPostId = postId;
此时的postId在 onLoad中,不能在onTap中使用,所以通过data:{}存取

在onTap中:

var postCollected = postsCollected[ this.data.currentPostId];
6.取反

postCollected = !postCollected;
7.重新绑定

postsCollected[ this.data.currentPostId] = postCollected;
wx.setStorageSync( "posts_collected", postsCollected);
this.setData({
collected: postCollected
})
按照上面获取数据的顺序重新绑定即可,最后还要重新this.setData绑定数据

猜你喜欢

转载自blog.csdn.net/weixin_40326021/article/details/79911959