vue中使用Betterscroll

安裝

npm install better-scroll --save

引入

import BScroll from 'better-scroll'

縱向滑動

<template>
	<div class="wrapper" ref="wrapper">
		<ul>
			<li v-for="item in 8">{{item}}</li>
		</ul>
	</div>
</template>
<script>
	import BScroll from 'better-scroll';
	export default {
		mounted() {
			this.$nextTick(() => {
				this.scroll = new BScroll(this.$refs.wrapper);
			});
		}
	};
</script>
<style type="text/css">
	.wrapper {
		overflow: hidden;
		height: 100vh;
	}
	
	ul li {
		height: 400px;
	}
</style>

橫向滾動

<template>
	<div class="tab" ref="tab">
		<ul class="tab_content" ref="tabWrapper">
			<li class="tab_item" v-for="item in itemList" ref="tabitem">
				{{item.title}}
			</li>
		</ul>
	</div>
</template>
<script>
	import BScroll from 'better-scroll';
	export default {
		data() {
			return {
				itemList: [{
						'title': '關注'
					},
					{
						'title': '推薦'
					},
					{
						'title': '深圳'
					},
					{
						'title': '視頻'
					},
					{
						'title': '音樂'
					},
					{
						'title': '熱點'
					},
					{
						'title': '新時代'
					},
					{
						'title': '娛樂'
					},
					{
						'title': '頭條號'
					},
					{
						'title': '問答'
					},
					{
						'title': '圖片'
					},
					{
						'title': '科技'
					},
					{
						'title': '體育'
					},
					{
						'title': '財經'
					},
					{
						'title': '軍事'
					},
					{
						'title': '國際'
					}
				]
			}
		},
		created() {
			this.$nextTick(() => {
				this.InitTabScroll();
			});
		},
		methods: {
			InitTabScroll() {
				let width = 0
				for(let i = 0; i < this.itemList.length; i++) {
					width += this.$refs.tabitem[0].getBoundingClientRect().width; //getBoundingClientRect() 返回元素的大小及其相對於視口的位置
				}
				this.$refs.tabWrapper.style.width = width + 'px'
				this.$nextTick(() => {
					if(!this.scroll) {
						this.scroll = new BScroll(this.$refs.tab, {
							startX: 0,
							click: true,
							scrollX: true,
							scrollY: false,
							eventPassthrough: 'vertical'
						});
					} else {
						this.scroll.refresh()
					}
				});
			}
		}
	};
</script>
<style scoped>
	.tab {
		width: 100vw;
		overflow: hidden;
		padding: 5px;
	}
	
	.tab .tab_content {
		line-height: 2rem;
		display: flex;
	}
	
	.tab_content .tab_item {
		flex: 0 0 60px;
		width: 60px;
		list-style: none;
	}
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章