用scroll-view
标签中的scroll-into-view
属性可以实现点击左侧分类栏控制商品
上代码
/**
我使用的wepy框架;开启了eslint 所以没有分号
data-id 不能直接是数字 所以我在前面拼了zxs
*/
<view>
<!-- 分类列表 -->
<scroll-view
scroll-y
scroll-with-animation
class="classify-list"
>
<repeat
for="{{list}}"
index="index"
item="item"
>
<view
class="item,{{index == navActive ? 'action' : ''}}"
@tap="bindClassify"
data-id="zxs{{index}}"
data-index="{{index}}"
>分类{{index}}</view>
</repeat>
</scroll-view>
<!-- 商品列表 -->
scroll-into-view 的参数一定要和分类id 一样
<scroll-view
scroll-y
scroll-with-animation
class="commodity-list"
@scroll="scroll"
scroll-into-view="{{contentActive}}"
>
<repeat
for="{{list}}"
index="index"
item="item"
>
<view
class="list"
id="zxs{{index}}"
>
<repeat
for="{{list}}"
index="subIndex"
item="subItem"
>
<view @tap="desc">
<image
src="图片地址"
lazy-load
mode="aspectFit"
/>
<view class="commodity-desc">
<h2>标题{{index}}</h2>
<text>标题描述{{contentActive}}~</text>
</view>
</view>
</repeat>
</view>
</repeat>
</scroll-view>
</view>
/** 事件函数*/
<script>
import wepy from 'wepy'
export default class Index extends wepy.page {
config = {
navigationBarTitleText: '标题'
}
data = {
navActive: '0',
contentActive: '',
info: [],
list: [],
height: []
}
methods = {
// 根据分类 调到相应的商品列
bindClassify (e) {
let id = e.currentTarget.dataset.id
let index = e.currentTarget.dataset.index
this.navActive = index
this.contentActive = id
},
// 监听商品滚动实现分类联动
scroll (event) {
let scrollTop = event.detail.scrollTop
for (let i = 0; i < this.height.length; i++) {
if (scrollTop >= 0 && scrollTop < this.height[0]) {
this.navActive = 0
} else if (scrollTop >= this.height[i]) {
this.navActive = i + 1
}
}
}
}
// 钩子
onLoad () {
const query = wx.createSelectorQuery()
const self = this
let arr = []
let s = 0
query.selectAll('.list').boundingClientRect(function (rect) {
rect.forEach((res) => {
s += res.height
arr.push(s)
})
self.height = arr
console.log(arr)
}).exec()
}
}
</script>
效果图
如有错误之处请留言;互相学习;共同进步。
如果有疑问欢迎留言