## **效果**
當滑動輪播圖時,swiper指示器會顯示輪播圖的總數和當前滑動輪播圖的順序,以及根據當前輪播圖顯示背景顏色。


## **輪播圖滑動實現**
組件`nav-carousel.vue`所要接收的數據類型為數組(`Array`)
```
carouselList:Array,
```
當`nav-carousel`組件從父組件接收到`carouselList`時,會通過`v-for`來進行循環,將`carouselList`中的每個對象賦值給`item`,在通過`item.src.`獲取到輪播圖片
```
v-for="(item, index) in carouselList" :key="index"
```
## **滑動顯示當前序號實現**
使用 $emit 觸發父組件的自定義事件,并傳入`event`的值,子組件中是通過`@change`來調用此方法的
```
swiperChange(e){
this.$emit("swiperChange", e)
}
```
設置`index`變量,將`event`中的`current`賦予給它
```
let index = e.detail.current;
```
通過綁定`index`來計算出當前顯示序號
```
this.swiperCurrent = index;
```
因為數組的索引是從`0`開始的,想要動態顯示第一張的序號,就必須進行加1操作
```
{{swiperCurrent+1}}
```
輪播圖總數:
輪播圖總數等于`carouselList`數組的長度
```
this.swiperLength = carouselList.length;
```
```
{{swiperLength}}
```
## **切換背景色**
當我們進入頁面時所看到的背景色為`carouselList`數組中的第`0`個`background`
```
this.titleNViewBackground = carouselList[0].background;
```
當頁面滑動時,背景色會隨著定義變量`index`的改變而改變
```
this.titleNViewBackground = this.carouselList[index].background;
```
## **輪播圖點擊事件**
使用 $emit 觸發父組件的自定義事件,并傳入`title`的值,子組件中是通過`@tap`來調用此方法的
```
navToDetailPage(title){
this.$emit("navToDetailPage",title)
},
```
父組件中定義變量`id`,因為測試數據沒有寫id,用title代替,通過`navigateTo`進行頁面跳轉并傳入`id`
```
uni.navigateTo({
url: `/pages/product/product?id=${id}`
})
```
在product頁面中的`onLoad`方法接收所傳入的`id`,為什么是`options.id`?
```
let id = options.id;
```
## **父組件源碼**
```
/**
* 請求靜態數據只是為了代碼不那么亂
* 分次請求未作整合
*/
async loadData() {
let carouselList = await this.$api.json('carouselList');
this.carouselList = carouselList;//數組賦值
this.titleNViewBackground = carouselList[0].background;
this.swiperLength = carouselList.length;
},
```
```
//輪播圖切換修改背景色
swiperChange(e) {
console.log(e)
let index = e.detail.current;
this.swiperCurrent = index;
this.titleNViewBackground = this.carouselList[index].background;
},
```
```
//詳情頁
navToDetailPage(title) {
//測試數據沒有寫id,用title代替
let id = title;
uni.navigateTo({
url: `/pages/product/product?id=${id}`
})
},
```
```
titleNViewBackground: '',
swiperCurrent: 0,
swiperLength: 0,
carouselList: [],
title:'輪播廣告'
```
```
<!-- 自定義swiper指示器 -->
<text class="num">{{swiperCurrent+1}}</text>
<text class="sign">/</text>
<text class="num">{{swiperLength}}</text>
```
```
<!-- 背景色區域 -->
<view class="titleNview-background" :style="{backgroundColor:titleNViewBackground}"></view>
```