小程序P126 02.商品列表-请求并渲染商品列表的数据
1、定义请求参数对象
①为了方便发起请求获取商品列表的数据,我们要根据接口的要求,事先定义一个请求参数对象:
data() {
return {
// 请求参数对象
queryObj: {
// 查询关键词
query: '',
// 商品分类Id
cid: '',
// 页码值
pagenum: 1,
// 每页显示多少条数据
pagesize: 10
}
}
}
②将页面跳转时携带的参数,转存到 queryObj 对象中:
onLoad(options) {
// 将页面参数转存到 this.queryObj 对象中
this.queryObj.query = options.query || ''
this.queryObj.cid = options.cid || ''
}
2、获取商品列表数据(图二)
①在 data 中新增如下的数据节点:
data() {
return {
// 商品列表的数据
goodsList: [],
// 总数量,用来实现分页
total: 0
}
}
②在 onLoad 生命周期函数中,调用 getGoodsList 方法获取商品列表数据:
onLoad(options) {
// 调用获取商品列表数据的方法
this.getGoodsList()
}
③在 methods 节点中,声明 getGoodsList 方法如下:
methods: {
// 获取商品列表数据的方法
async getGoodsList() {
// 发起请求
const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
if (res.meta.status !== 200) return uni.$showMsg()
// 为数据赋值
this.goodsList = res.message.goods
this.total = res.message.total
}
}