1. 程式人生 > 其它 >uniApp實現swiper和scroll-view聯動,滑動swiper時改變scroll-view,點選scroll-view時切換到指定的swiper(初學者)

uniApp實現swiper和scroll-view聯動,滑動swiper時改變scroll-view,點選scroll-view時切換到指定的swiper(初學者)

<template>
<!-- 這裡的注意點,使用 scroll-view時,如果想讓元素橫向也就是X軸排列的話
要注意以下幾點:
1、scroll-view不支援flex,預設block;
2、scroll-view設定scroll-x="true"; width: 100%; white-space: nowrap;(這個屬性很重要,能不能滑動都看這個屬性)
3、子元素設定display: inline-block;
4、子元素內容寬度要超出scroll-view的寬。
-->
<view>
<!-- 設定scroll-view的scroll-x="true",為X軸滑動 -->
<scroll-view scroll-x="true" class="scroll-view" style=" white-space: nowrap;">
<!-- 子元素選擇用v-for進行迴圈遍歷,因為後面要用到index -->
<view class="body-view" v-for="(item,index) in scrollViewList" :key="index" @click="changeSwiper(index)">
<!-- 這裡是一個小提醒點,動態繫結class的值,一個三元表示式 -->
<view :class="[currentTab==index ? 'menu-one-act' : 'menu-one']">
{{item}}
</view>
</view>
</scroll-view>
<!-- swiper這邊設定禁用指示點,禁止自動輪播,動態設定swiper的current屬性,以便和scroll-view進行對接,在設定一個輪播切換事件
當swiper改變時,觸發函式
-->
<swiper :indicator-dots="false" :autoplay="false" class="swiper" :current="currentTab" ref="swiper" @change="changeScroll">
<block v-for="(item,index) in scrollViewList" :key="index">
<swiper-item>
<scroll-view scroll-y="true" class="swiper-scroll">
<view class="swiper-item">{{item}}</view>
</scroll-view>
</swiper-item>
</block>
</swiper>
</view>
</template>

<script>
export default {
data() {
return {
//定義swiper的初始值為0,也就是第一頁
currentTab: 0,
//再定義一個數組,存放資料
scrollViewList: ["頻道", "分割槽", "分割槽", "分割槽", "分割槽",'111']
}
},
onLoad() {
uni.getSystemInfo({ //獲取系統資訊
success: (res) => {
this.swiperHeight = res.windowHeight + 'px'
},
fail: (res) => {
console.log('error')
}
})
},
methods: {
// 切換swiper時,改變scroll的函式
changeScroll: function(e) {
// 令data中定義的currentTab等於當前swiper的current的值,來改變scroll
this.currentTab = e.target.current;
},
changeSwiper: function(index) {
// 點選scroll,將返回的引數賦值給currentTab
if (this.currentTab == index) {
return false;
} else {
this.currentTab = index;
}
}
}
}
</script>

<style>
page {
width: 100%;
height: 90%;
}

.body-view {
display: inline-block;
width: 150rpx;
height: 60rpx;
background-color: #007AFF;
}

.scroll-view {
text-align: center;
width: 100%;
white-space: nowrap;
}

.menu-one {
background-color: green;
height: 100%;
}

.menu-one-act {
background-color: blue;
height: 100%;
}

.swiper {
height: 2000px;
text-align: center;
background-color: #DD524D;
}

.swiper-scroll {
height: 100%;
}
</style>