直播商城源码,实现左右联动商品分类页面
一、搭建结构
重点:使用uniapp的scroll-view组件,如果是小程序原生开发也是这个组件;其次如果是html开发,就自己实现一个溢出滚动。
废话不多说,上代码:
<template>
<view class="u-wrap">
<view class="u-menu-wrap">
<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
:scroll-into-view="itemId">
<view v-for="(item,index) in tabbar" :key="index" class="u-tab-item" :class="[current == index ? 'u-tab-item-active' : '']"
@tap.stop="swichMenu(index)">
<text class="u-line-1">{
{
item.name}}</text>
</view>
</scroll-view>
<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box" @scroll="rightScroll">
<view class="page-view">
<view class="class-item" :id="'item' + index" v-for="(item , index) in tabbar" :key="index">
<view class="item-title">
<text>{
{
item.name}}</text>
</view>
<view class="item-container">
<view class="thumb-box" v-for="(item1, index1) in item.foods" :key="index1" @click="featureC(item1.cat, item1.name)">
<image v-if="item1.icon != ''" class="item-menu-image" :src="item1.icon" mode=""></image>
<view v-else class="item-menu-image row-c" style="background-color: #F4F6F8;"><text style="font-size: 20rpx;color: #d0d0d0;">加载失败</text></view>
<view class="item-menu-name">{
{
item1.name}}</view>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
</view>
</template>
JavaScript业务逻辑代码:
data() {
return {
scrollTop: 0, //tab标题的滚动条位置
oldScrollTop: 0, // tab标题的滚动条旧位置
current: 0, // 预设当前项的值
menuHeight: 0, // 左边菜单的高度
menuItemHeight: 0, // 左边菜单item的高度
itemId: '', // 栏目右边scroll-view用于滚动的id
tabbar: JSON.parse(uni.getStorageSync('categroy')), // 渲染的数据,放在最后供你们测试
arr: [], // 储存距离顶部高度的数组
scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
timer: null // 定时器
}
}
二、添加逻辑层业务
分别获取左侧和右侧每一个类别的高度
我们知道,在uniapp里面没有window对象和dom元素,所以如果我们要获取页面上的一些节点信息时,需要通过uni.createSelectorQuery()这个API来获取,这里不再赘述。—— 《传送地址》
/**
* 获取一个目标元素的高度
* @elClass 元素的类名
* @dataVal 储存高度的对象
*/
methods: {
getElRect(elClass, dataVal) {
new Promise((resolve, reject) => {
const query = uni.createSelectorQuery().in(this);
query.select('.' + elClass).fields({
size: true
}, res => {
// 如果节点尚未生成,res值为null,循环调用执行
if (!res) {
setTimeout(() => {
this.getElRect(elClass);
}, 10);
return;
}
this[dataVal] = res.height;
resolve();
}).exec();
})
}
}
计算右侧每个分类距离顶部的高度并保存
onReady() {
this.getMenuItemTop()
},
mehods: {
/**
* 获取右边菜单每个item到顶部的距离
* 储存到 arr 数组里面用于后面滚动判断
*/
getMenuItemTop() {
new Promise(resolve => {
let selectorQuery = uni.createSelectorQuery();
selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
// 如果节点尚未生成,rects值为[](因为用selectAll,所以返回的是数组),循环调用执行
if(!rects.length) {
setTimeout(() => {
this.getMenuItemTop();
}, 10);
return ;
}
rects.forEach((rect) => {
// 视情况而定,这里减去rects[0].top,是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
// this.arr.push(rect.top - rects[0].top);
this.arr.push(rect.top)
resolve();
})
}).exec()
})
},
}
以上就是直播商城源码,实现左右联动商品分类页面, 更多内容欢迎关注之后的文章