持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情
安装环境
npm install better-scroll -S
看一下大致思路
编辑
编辑
代码部分:
updated() {
if (!this.scroll) {
this.$nextTick(() => {
this.scroll = new BetterScroll(this.$refs.right, {
click: true,
probeType: 3,
// pullUpload:true上拉加载更多
});
// 滚动事件
this.scroll.on("scroll", (pos) => {
console.log(pos);
this.scrollY = Math.abs(pos.y);
console.log(this.scrollY);
});
this.leftClick();
console.log(this.scroll);
});
}
},
methods:{
leftClick() {
let uls = this.$refs.right.getElementsByClassName("li");
console.log(uls);
let height = 0;
this.allHeight.push(height);
Array.from(uls).forEach((v) => {
height += v.clientHeight;
// console.log(v.clientHeight);
this.allHeight.push(height);
});
},
onChange(index) {
console.log(this.allHeight[index]);
this.scroll.scrollTo(0, -this.allHeight[index], 300);
// ul.scrollTop = this.allHeight[index] + 10;
},
}
computed: {
current(){
console.log(111);
return this.allHeight.findIndex((item,index)=>{
console.log(item,index);
// 滚动距离
// 1500>= 1400 && 1500< 2100
return this.scrollY >= item && this.scrollY <this.allHeight[index + 1]
})
}
},
左侧按钮标签
<li
v-for="(item, index) in list"
@click="onChange(index)"
:key="index"
:class="{lis_one_color:index == current}"
class="lis_one "
>
左侧按钮的css样式
.lis_one{
font-weight: bold;
text-align: center;
font-size: 18px;
/* width: 100%; */
height: 50px;
line-height: 36px;
margin: 10px 0;
padding: 7px 0;
box-sizing: border-box;
}
.lis_one_color{
color: rgb(255,102,0) ;
border-left:3px rgb(255,102,0) solid;
}
引入better-scroll
import BetterScroll from "better-scroll";
注意: 需要用到better-scroll的属性有
click:true,
probeType:3
使用nextTick进行延迟回调
nextTick
定义: 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
updated() {
if (!this.scroll) {
this.$nextTick(() => {
this.scroll = new BetterScroll(this.$refs.right, {
click: true,
probeType: 3,
});
}
},
因为每次获取到的y轴为负值,所以要通过abs转换成正数
this.scroll.on("scroll", (pos) => {
console.log(pos);
this.scrollY = Math.abs(pos.y);
console.log(this.scrollY)
});
computed: {
current(){
return this.allHeight.findIndex((item,index)=>{
console.log(item,index);
})
}
},
思路大致就是这样,如有不懂的地方或者其他更好的写法我们可以进一步探讨一下
效果如下: