借用网易云api练手vue,做了一个网页版本的音乐软件,需要横向滚动,纵向滚动。
滚动采用的是Batter-Scroll
1. 安装
npm install @better-scroll/core --save
// or
yarn add @better-scroll/core
复制代码
2. 引用
import BScroll from '@better-scroll/core'
复制代码
3. 竖向滚动实现
竖向的滚动比较容易实现
<template>
<div class="wrapper" ref="wrapper">
<slot></slot>
</div>
</template>
<script>
import BScroll from "@better-scroll/core";
export default {
props: {
top: {
type: Number,
default: 0,
},
list: {
type: Array,
required: true,
},
},
mounted() {
this.initScroll();
},
//图片是通过api接口异步获得的,初始化时没有被写入进去,盒子的高度比页面高度小,导致不能滚动,所以要监听list表单,通过this.$nextTick对BScroll组件刷新。
watch: {
list() {
this.$nextTick(() => {
this.refresh();
});
},
},
beforeUnmount() {
this.scroll.destroy()
},
methods: {
initScroll() {
this.$refs.wrapper.style.top = this.top + "px";
this.scroll = new BScroll(this.$refs.wrapper); //初始化BScroll
},
refresh() {
this.scroll && this.scroll.refresh();
},
},
};
</script>
<style>
.wrapper {
position: absolute;
overflow: hidden; /*一定要隐藏自带的滚动*/
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
复制代码
注意: 盒子高度一定要大于页面的高度,不然不会滚动,有像我一样异步获取数据的,一定要在数据加载完成后刷新,不然可能造成不能滚动现象。
4. 实现横向滚动
<template>
<div class="horizontal-container">
<div class="scroll-wrapper" ref="scroll">
<div class="scroll-content">
<div
class="scroll-item"
v-for="(item, index) in dargonList"
:key="index"
>
<div class="icon">
<img :src="item.iconUrl" @load="imgLoad" />
</div>
<div>
{{ item.name }}
</div>
</div>
</div>
</div>
</div>
</template>
<script type="text/ecmascript-6">
import BScroll from '@better-scroll/core'
export default {
props: {
dargonList: {
type: Array,
required: true,
},
},
mounted() {
this.init()
},
beforeUnmount() {
this.bs.destroy()
},
methods: {
init() {
this.bs = new BScroll(this.$refs.scroll, {
scrollX: true, //横向滚动需要添加的条件
probeType: 3
})
},
imgLoad() {
this.bs.refresh(); //等图片加载完刷新
}
}
}
</script>
<style lang="scss" scoped>
.horizontal-container {
}
.scroll-wrapper {
position: relative;
width: 100%;
white-space: nowrap; /* 必备 */
overflow: hidden;
}
.scroll-content {
display: inline-block; /* 必备 */
}
.scroll-item {
font-size: 12px;
display: inline-block; /* 必备 */
text-align: center;
padding: 0 15px;
}
.icon {
width: 50px;
height: 50px;
background: #fdedf0;
border-radius: 50px;
margin: 5px 0;
}
.icon > img {
width: 50px;
filter: invert(52%) sepia(82%) saturate(5725%) hue-rotate(334deg)
brightness(100%) contrast(106%); /* #fe3a40#fdedf0 */
}
</style>
复制代码
横向滚动比纵向滚动复杂,文档中强调 对CSS 是比较苛刻的。首先你要保证 wrapper 不换行,并且 content 的 display 是 inline-block。
5. 总结:Better-Scroll用下来还算简单,没有太多的坑,注意的点就是初始化后页面有没有完全被写入,可以通过在网页查看源码观察是否被写入进去。
自己是个小白,有不对的地方请多指教,欢迎大家讨论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END