写在前面:最近几天帮我姐完善小程序的开发,虽然进度才一丢丢(ps:我好多作业还没做,嘤嘤嘤),现在遇到的问题是,一个商品分六类,其中每类又有很多种类,为了实现点击商品跳转到商品详情页,需要获得每个商品的信息并显示出来,所含数据之多,用全局变量就不太聪明的样子,总的来说在这上面花费了我一些时间,得记录下来。小程序和HTML不太一样,枯萎o(╥﹏╥)o。
如果大佬有更好的办法,一定和我联系!!教教我
第一次尝试
采用的是网上普遍都有的教程,传参,通过在url后面加上key和value的值,然而,生而为人我很抱歉,传过去的参数工具提示undefined,修改多次,无果,我的时间啊!!其实仔细想想这个也不太聪明的样子,传参传的信息也不能太长,不适合商品类的项目开发,索性放弃。思考了一会,决定使用本地缓存的方式,所以有了
第二次尝试
我的做法是在点击商品跳转时把商品信息写入本地缓存:
<view class="inventory">
<view class="inventoryitem" data-name="{{rose99}}" data-url="{{item.url}}" data-id="{{item.id}}"
bindtap="itemTap" wx:for="{{rose99}}" wx:key="logs1">
<image class="pic" src="{{item.icon}}.jpg" mode="aspectFill"></image>
<view class="description"> {{item.text}} </view>
<view class="description2"> {{item.price}} </view>
</view>
</view>
其中name是商品大类信息的数组(里面包含了读个商品及其详细信息),url是点击商品跳转至的页面,id是为了通过相应的数组索引跳转至正确的详细商品页面,js包含了跳转和缓存数据到本地两个步骤:
其中:wx.setStorage()实现本地缓存
itemTap: function (e) {
var key=e.currentTarget.dataset.data
wx.setStorage({
key:"id",
data:e.currentTarget.dataset.id
})
wx.setStorage({
key:'key',
data:e.currentTarget.dataset.name
})
wx.navigateTo({
url: `${e.currentTarget.dataset.url}`,
success: function (res) {
// success
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
在跳转至的页面item,定义了一个数组info来获取本地缓存(wx.getStorageSync)的信息:
data: {
info:[]
},
item同时写了一个函数来赋值给info:
fetchData: function () {
let ids=wx.getStorageSync('id')
let name=wx.getStorageSync('key')
var src=name[ids].icon
var text=name[ids].text
var price=name[ids].price
this.setData({
info:[
{
id:ids,
price:price,
src:src,
text:text,
}
]
})
},
最后在item.xtml,正常绑定数据就OK了:
<view class="container" wx:for="{{info}}" wx:key="items">
<view class="topBar">
<image src="{{item.src}}" mode="aspectFill"></image>
</view>
<view class="name"><text>{{item.text}}\n</text> </view>
<text class="name"><text class="price">{{item.price}}</text></text>
<view class="information">
<text class="price">支持预定\n</text>
<text class="name">适用场景:\n</text>
<text class="name">使用对象:\n</text>
<text class="name">主花材:玫瑰\n</text>
<text class="name">配送:商家自配\n</text>
<text class="name">活动:暂无\n</text>
<button>购买</button>
</view>
</view>
最后的最后,记得清除缓存啊。
以上。