分类点击到商品指定位置
data添加currentIndex
data() {
return {
active: 0,
categories: [],
positions: [],
currentIndex: 0
};
mounted页面加载完成计算positions
mounted(){
const categories = kfc['categories'];
// for (let index=0; index < categories.length; index++){
// const category = categories[index];
// this.categories.push({id:category.id,name:category.name})
// }
this.categories = categories
this.$nextTick(() => {
var menuScroll = new BScroll(this.$refs.category,{
scrollY: true,
click: true
})
var goodsScroll = new BScroll(this.$refs.goods,{
scrollY: true,
click: true
})
this.menuScroll = menuScroll;
this.goodsScroll = goodsScroll;
const positions = [0];
let offset = 0;
const dlList = document.getElementsByClassName('goods-dl');
for(let dl of dlList){
const height = dl.clientHeight;
offset += height;
positions.push(offset);
}
this.positions = positions;
})
},
给分类添加点击滚动方法
methods: {
categoryClick(index){
const position = this.positions[index]
// 滚动的时候,如果想要望上面滚动 y要为负数
this.goodsScroll.scrollTo(0, -position, 500)
this.currentIndex = index
}
点击事件和点击高亮
<li v-for="(category, index) in categories" :key="category.name" @click="categoryClick(index)" :class="index==currentIndex?'active':''">
{{category.name}}
</li>
css高亮样式添加
li{
height: 50px;
line-height: 50px;
&.active{
background-color: #ccc;
}
效果图
滚动商品到分类到指定位置
mounted(){
const categories = kfc['categories'];
// for (let index=0; index < categories.length; index++){
// const category = categories[index];
// this.categories.push({id:category.id,name:category.name})
// }
this.categories = categories
this.$nextTick(() => {
var menuScroll = new BScroll(this.$refs.category,{
scrollY: true,
click: true
})
var goodsScroll = new BScroll(this.$refs.goods,{
scrollY: true,
click: true,
// 设置probeType为2,监听scroll事件
probeType: 2
})
goodsScroll.on('scroll',(pos) => {
const y = Math.abs(pos.y);
const positions = this.positions;
for (let index = positions.length-1; index >= 0; index-- ) {
const position = positions[index];
if (y >= position){
this.currentIndex = index;
break
}
}
})
this.menuScroll = menuScroll;
this.goodsScroll = goodsScroll;
const positions = [0];
let offset = 0;
const dlList = document.getElementsByClassName('goods-dl');
for(let dl of dlList){
const height = dl.clientHeight;
offset += height;
positions.push(offset);
}
this.positions = positions;
})
},
实现效果图