<template>
	<view>
		<u-swiper :list="slides" name="img_url" height="320rpx"></u-swiper>
		<!-- 选项卡 -->
		<view class="u-text-center u-m-t-30">
			<u-tabs :list="sortList" bar-width="80" item-width="160" :current="currentSort" 
			@change="changeSort"></u-tabs>
		</view>
		<u-row gutter="16" class="u-skeleton">
			<!-- 一共12格子,一行显示两个商品 -->
			<u-col span="6" v-for="(goods,index) in  goodsList" :key="index">
				<goods_card :goods="goods"></goods_card>
			</u-col>
		</u-row>
		<u-skeleton :loading="loading" :animation="true" bgColor="#FFF"></u-skeleton>
	</view>
</template>
<script>
	export default {
		data() {
		return {
			sortList: [
				{name: '默认'},
				{name: '销量'},
				{name: '推荐'},
				{name: '最新'},
			],
			currentSort: 0,
			// 轮播图数据
			slides: [],
			// 下面商品数据
			goodsList: [{},{},{},{}],
			// 页面
			page: 1,
			// 是否显示骨架屏
			loading: true
		}
		},
		onLoad() {
		this.getData()
		},
		methods: {
			// 点击中间的选项卡触发函数
			changeSort(index){
				// index为选项卡的编号,第一个为0
				console.log(index);
				// currentSort不同就可以根据不同的编号来确定筛选条件
				this.currentSort = index
				// 先初始化商品数据页和分页,在获取数据
				this.goodsList = [{},{},{},{}]
				this.page = 1
				this.getData()
			},
			async getData(){
				// 显示骨架屏
				this.loading = true
				
				const params = {
					page: this.page
				}
				if(this.currentSort == 1) {params.sales = 1}
				else if(this.currentSort == 2) {params.recommend = 1} 
				else if(this.currentSort == 3) {params.new = 1}
				const res = await this.$u.api.index(params)
				// 骨架屏隐藏
				this.loading = false
				console.log(res);
				// 做优化,下拉加载更多的时候,vue会把新数据和已有虚拟dom做对比,
				// 如果轮播图没有改变,就不会接收轮播图的数据
				this.slides = res.slides
				this.goodsList = this.goodsList.pop().title  ?  [...this.goodsList,...res.goods.data]  : [...res.goods.data] 
			}
		},
		onReachBottom(){
			this.page = this.page + 1
			this.getData()
		}
	}
</script>
<style lang="scss" scoped>
</style>
<p>该代码是一个小程序页面的代码,主要实现了轮播图和商品列表的展示,并且可以根据选项卡的选择来确定商品的排序方式。具体解析如下:</p>
<ol>
<li>数据部分:</li>
</ol>
<p>(1)sortList:选项卡的数据,包括4个选项卡的名称。</p>
<p>(2)currentSort:当前选中的选项卡的编号,初始值为0。</p>
<p>(3)slides:轮播图的数据,初始值为空。</p>
<p>(4)goodsList:商品列表的数据,初始值为4个空对象。</p>
<p>(5)page:商品列表的页码,初始值为1。</p>
<p>(6)loading:是否显示骨架屏的状态,初始值为true。</p>
<ol start="2">
<li>生命周期:</li>
</ol>
<p>(1)onLoad:页面加载时调用getData函数获取数据。</p>
<ol start="3">
<li>方法部分:</li>
</ol>
<p>(1)changeSort:点击选项卡时触发的函数,用于改变currentSort的值并重新请求数据。</p>
<p>(2)getData:获取数据的函数,根据currentSort的值构造不同的请求参数,请求后更新slides和goodsList的数据。</p>
<p>(3)onReachBottom:上拉触底时调用getData函数获取更多数据。</p>
<ol start="4">
<li>请求参数:</li>
</ol>
<p>请求参数包括page(商品列表的页码)、sales(是否按销量排序)、recommend(是否按推荐排序)、new(是否按新品排序)。</p>
<ol start="5">
<li>返回数据:</li>
</ol>
<p>返回数据包括slides(轮播图的数据)和goods(商品列表的数据),其中goods又包括多个商品的数据,每个商品的数据包括title(商品名称)、price(商品价格)、sales(商品销量)等信息。</p>
热门商品推荐 - 精选好物,限时抢购

原文地址: https://www.cveoy.top/t/topic/oysF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录