因为公司后端用其他框架,所以都是用cdn引用js写在一个页面了,现在只能达到点击左侧栏目、右侧到对应的栏目位置,但是右侧滑动的时候,左边栏目不跟随切换active
是右边li的索引值没有传到左边去吗?但是左边可以获取右边的索引了,点击也可以联动
html代码
<div class="content">
<!--左边-->
<div class="menu-wrapper" ref="menuWrapper">
<ul>
<li v-for="(food,index) in foods" @click="menuClick(index,$event)" :class="{'active': activeIndex == index}">
{{food.class}}
<i class="num"></i>
</li>
</ul>
</div>
<!--右边-->
<div class="foods-wrapper" id="wrapper" ref="foodsWrapper">
<ul>
<li v-for="(food,index) in foods" :key="food.id" class="food-list-hook">
<div class="class-title">
{{food.class}}
</div>
<div v-for="food in food.list">
<div class="item">
<div class="itemleft" @click="menuShow(food)">
<div class="item-img">
<img :src="food.imgs" alt="">
</div>
</div>
<div class="itemright">
<div class="title">
{{food.name}}
</div>
<div class="price">
<i class="fa fa-cny"></i>
<span>
{{food.price}}
</span>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
js代码
new Vue({
el: '#app',
data() {
return {
foods: [],
listHeight: [],
foodsScrollY: 0
}
},
created() {
axios.get('data.json').then(response = >{
this.foods = response.data.foods;
this.$nextTick(() = >{
this._initScroll(); // 初始化scroll
this._calculateHeight(); // 初始化列表高度列表
})
});
},
computed: {
activeIndex() {
for (let i = 0; i < this.listHeight.length; i++) {
let topHeight = this.listHeight[i] let bottomHeight = this.listHeight[i + 1]
if (!bottomHeight || (this.foodsScrollY >= topHeight && this.foodsScrollY < bottomHeight)) {
return i
}
}
return 0
}
},
methods: {
_initScroll() {
this.menuWrapper = new BScroll(this.$refs.menuWrapper, {
click: true
});
this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
probeType: 3
});
// 监控滚动事件
this.foodsScroll.on('scroll', (pos) = >{
this.foodsScrollY = Math.abs(Math.round(pos.y))
})
},
_calculateHeight() {
let foodList = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook');
let height = 0 this.listHeight.push(height) for (let i = 0; i < foodList.length; i++) {
let item = foodList[i] height += item.clientHeight this.listHeight.push(height)
}
},
menuClick(index, event) {
if (!event._constructed) {
return
}
this.foodsScroll.scrollTo(0, -this.listHeight[index], 300)
}
}
});