这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战
上一篇文章我们完成了商品列表页面的制作,本篇将继续编写商品详情页面,以及完成列表页面向详情页面的跳转。将要涉及的知识点有:小程序中带参数的链接跳转,带参数中网络请求,评价模块的vant组件使用。
商品详情页
新建pages>detail文件夹,编写对应的wxml,json,js,wxss等文件。由于这不是本篇重点,所以就不详细介绍了。直接贴代码:
<!--pages/detail/detail.wxml-->
<view class="detail-box">
<view class="goods-detail">
<image src="{{detailData.picUrl}}" mode="aspectFit"></image>
<view class="goods-info">
<view class="name">{{detailData.name}}</view>
<view class="brief">{{detailData.brief}}</view>
</view>
</view>
<view class="comment">
<view class="input-area">
<van-field value="{{ comment }}" placeholder="写点评价吧" bind:change="onCommentChange" />
</view>
<view class="rate-area">
<van-rate value="{{ rate }}" bind:change="onRateChange" />
</view>
<view class="upload-area">
<van-button type="warning" bindtap="uploadImage">上传图片</van-button>
</view>
<view>
<image class="uploadimages" wx:for="{{imagesData}}" wx:key="index" src="{{item}}"></image>
</view>
</view>
<view class="submit">
<van-button type="primary" bindtap="submit">提交</van-button>
</view>
</view>
带参数跳转
实现微信小程序页面的跳转,有以下几种方法给大家分享:
- 使用导航组件,标签,页面链接来实现(该方法点击时有背景)
- 给页面布局加监听bindtap事件,然后在方法里面,通过wx.navigatorTo来实现跳转(保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面)
- 通过wx.redirectTo实现跳转(关闭当前页面,跳转到应用内某个页面)
- 通过wx.navigateBack返回上一级(关闭当前页面,返回上一页面或多级页面)。
本篇将主要介绍第二种方法,在列表页index.wxml中加监听bindtap事件:
<button data-goodsId="{{item.id}}" bindtap="gotoComment">去评价</button>
在列表页index.js中实现跳转
gotoComment: function(event) {
let goodIndex = event.target.dataset.goodsid
wx.navigateTo({
url: '../detail/detail?goodIndex='+goodIndex,
})
}
接收参数并发送请求
在接收页面,我们在生命周期函数onLoad中获取前一个页面传递过来的参数,调用云函数以实现请求详情页。
onLoad: function (options) {
console.log(options.goodIndex)
wx.cloud.callFunction({
name: 'goodsdetail',
data: {
goodIndex: options.goodIndex
}
}).then(res => {
this.setData({
detailData: JSON.parse(res.result).data.info
})
}).catch(err => {
wx.showToast({
title: '失败了',
})
})
}
由于涉及网络请求,我们依然新建云函数goodsdetail,安装promise request(具体方法可见上一篇)请求数据的方式如下:
exports.main = async (event, context) => {
return rp(`https://iyouquan.capelabs.cn/yfwx/goods/detail?id=${event.goodIndex}`)
.then(function (res) {
return res
})
.catch(function (err) {
// Crawling failed...
});
}
评价模块
该模块是云开发使用的重点模块,本篇先编写出初始静态页面,下一篇我们将具体讲解如何完成对商品的评价,评价图片上传到云存储,评价内容保存到云数据库同时涉及使用Promise处理JS异步问题。
引用vant组件
在对应的detail.json中引用vant组件:
{
"component": true,
"usingComponents": {
"van-field": "@vant/weapp/field/index",
"van-button": "@vant/weapp/button/index",
"van-rate": "@vant/weapp/rate/index"
}
}
使用Vant组件
在对应的detail.wxml中引用vant组件:
<van-field value="{{ comment }}" placeholder="写点评价吧" bind:change="onCommentChange" />
<van-rate value="{{ rate }}" bind:change="onRateChange" />
<van-button type="warning" bindtap="uploadImage">上传图片</van-button>