long-list.uvue 9.3 KB
Newer Older
1
<template>
雪洛's avatar
雪洛 已提交
2
  <scroll-view ref="pageScrollView" class="page" :rebound="false"
3 4
    @startnestedscroll="onStartNestedScroll" @nestedprescroll="onNestedPreScroll">
    <view ref="header" class="search-bar">
5
      <input placeholder="搜索..." maxlength="-1"/>
6 7
    </view>
    <view class="swiper-list">
雪洛's avatar
雪洛 已提交
8
      <scroll-view ref="tabScroll" class="swiper-tabs" direction="horizontal" :show-scrollbar="false">
9
        <view class="flex-row" style="align-self: flex-start;">
10
          <text ref="swipertab" space="nbsp" class="swiper-tabs-item" :class="swiperIndex==index ? 'swiper-tabs-item-active' : ''"
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
            v-for="(item, index) in swiperList" :key="index" @click="onTabClick(index)">
            {{item.name}}
          </text>
        </view>
        <view ref="indicator" class="swiper-tabs-indicator"></view>
      </scroll-view>
      <swiper ref="swiper" class="swiper-view" :current="swiperIndex" @transition="onSwiperTransition"
        @animationfinish="onSwiperAnimationfinish">
        <swiper-item class="swiper-item" v-for="(item, index) in swiperList" :key="index">
          <long-page ref="longPage" :type="item.type" :preload="item.preload"></long-page>
        </swiper-item>
      </swiper>
    </view>
  </scroll-view>
</template>

<script>
  import longPage from './long-list-page.uvue';

  type SwiperTabsItem = {
    x : number,
    w : number
  }

  type SwiperViewItem = {
    type : string,
    name : string,
    preload : boolean,
  }

  /**
   * 根据权重在两个值之间执行线性插值.
   * @constructor
   * @param {number} value1 - 第一个值,该值应为下限.
   * @param {number} value2 - 第二个值,该值应为上限.
   * @param {number} amount - 应介于 0 和 1 之间,指示内插的权重.
   * @returns {number} 内插值
   */
  function lerpNumber(value1 : number, value2 : number, amount : number) : number {
    return (value1 + (value2 - value1) * amount)
  }

  export default {
    components: {
      longPage
    },
    data() {
      return {
        swiperList: [
          {
            type: 'UpdatedDate',
            name: '最新上架',
            preload: true
64
          },
65 66 67 68
          {
            type: 'FreeHot',
            name: '免费热榜',
            preload: false
69
          },
70 71 72 73
          {
            type: 'PaymentHot',
            name: '付费热榜',
            preload: false
74
          },
75 76 77 78
          {
            type: 'HotList',
            name: '热门总榜',
            preload: false
79
          }
80
        ] as SwiperViewItem[],
雪洛's avatar
雪洛 已提交
81
        swiperIndex: 0,
雪洛's avatar
雪洛 已提交
82 83 84 85 86 87 88
        pageScrollView: null as null | UniElement,
        headerHeight: 0,
        animationFinishIndex: 0,
        tabScrollView: null as null | UniElement,
        indicatorNode: null as null | UniElement,
        swiperWidth: 0,
        swiperTabsRect: [] as SwiperTabsItem[]
89 90 91
      }
    },
    onReady() {
雪洛's avatar
雪洛 已提交
92 93 94 95
      this.pageScrollView = this.$refs['pageScrollView'] as UniElement;
      this.headerHeight = (this.$refs['header'] as UniElement).offsetHeight
      this.tabScrollView = this.$refs['tabScroll'] as UniElement
      this.indicatorNode = this.$refs['indicator'] as UniElement
96
      (this.$refs["swiper"] as UniElement).getBoundingClientRectAsync()!.then((res : DOMRect) : Promise<void> => {
H
hdx 已提交
97 98 99 100 101
        this.swiperWidth = res.width
        return this.cacheTabItemsSize()
      }).then(() => {
        this.updateTabIndicator(this.swiperIndex, this.swiperIndex, 1)
      });
102 103 104 105 106 107 108 109 110 111 112 113 114
    },
    onPullDownRefresh() {
      (this.$refs["longPage"]! as ComponentPublicInstance[])[this.swiperIndex].$callMethod('refreshData', () => {
        uni.stopPullDownRefresh()
      })
    },
    methods: {
      // TODO
      onStartNestedScroll(_ : StartNestedScrollEvent) : boolean {
        return true
      },
      onNestedPreScroll(event : NestedPreScrollEvent) {
        const deltaY = event.deltaY
雪洛's avatar
雪洛 已提交
115
        const scrollTop = this.pageScrollView!.scrollTop
116 117 118 119 120

        // 优先处理父容器滚动,父容器不能滚动时滚动子

        if (deltaY > 0) {
          // 向上滚动,如果父容器 header scrollTop < offsetHeight,先滚动父容器
雪洛's avatar
雪洛 已提交
121 122
          if (scrollTop < this.headerHeight) {
            const difference = this.headerHeight - scrollTop - deltaY
123
            if (difference > 0) {
雪洛's avatar
雪洛 已提交
124
              this.pageScrollView!.scrollBy(event.deltaX, deltaY)
125 126 127 128
              event.consumed(event.deltaX, deltaY)
            } else {
              const top : number = deltaY + difference
              event.consumed(event.deltaX, top.toFloat())
雪洛's avatar
雪洛 已提交
129
              this.pageScrollView!.scrollBy(event.deltaX, top.toFloat())
130 131 132 133 134 135
            }
          }
        } else if (deltaY < 0) {
          // 向下滚动,如果父容器 scrollTop > 0,通知子被父容器消耗,然后滚动到 0
          if (scrollTop > 0) {
            event.consumed(event.deltaX, deltaY)
雪洛's avatar
雪洛 已提交
136
            this.pageScrollView!.scrollBy(event.deltaX, deltaY)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
          }
        }
      },
      onTabClick(index : number) {
        this.setSwiperIndex(index, false)
      },
      onSwiperTransition(e : SwiperTransitionEvent) {
        // 微信 skyline 每项完成触发 Animationfinish,偏移值重置
        // 微信 webview 全部完成触发 Animationfinish,偏移值累加
        // 在滑动到下一个项的过程中,再次反向滑动,偏移值递减
        // uni-app-x 和微信 webview 行为一致

        const offset_x = e.detail.dx

        // 计算当前索引并重置差异
雪洛's avatar
雪洛 已提交
152 153 154
        const current_offset_x = offset_x % this.swiperWidth
        const current_offset_i = offset_x / this.swiperWidth
        const current_index = this.animationFinishIndex + parseInt(current_offset_i + '')
155 156 157 158 159 160 161 162 163 164

        // 计算目标索引及边界检查
        let move_to_index = current_index
        if (current_offset_x > 0 && move_to_index < this.swiperList.length - 1) {
          move_to_index += 1
        } else if (current_offset_x < 0 && move_to_index > 0) {
          move_to_index -= 1
        }

        // 计算偏移百分比
雪洛's avatar
雪洛 已提交
165
        const percentage = Math.abs(current_offset_x) / this.swiperWidth
166 167 168 169 170 171 172 173 174

        // 通知更新指示线
        this.updateTabIndicator(current_index, move_to_index, percentage)

        // 首次可见时初始化数据
        this.initSwiperItemData(move_to_index)
      },
      onSwiperAnimationfinish(e : SwiperAnimationFinishEvent) {
        this.setSwiperIndex(e.detail.current, true)
雪洛's avatar
雪洛 已提交
175
        this.animationFinishIndex = e.detail.current
176
      },
H
hdx 已提交
177 178
      async cacheTabItemsSize() {
        this.swiperTabsRect.length = 0;
DCloud-yyl's avatar
DCloud-yyl 已提交
179
        const tabs = this.$refs["swipertab"] as UniElement[]
H
hdx 已提交
180 181
        for (let i = 0; i < tabs.length; i++) {
          const element = tabs[i];
182
          const rect = await element.getBoundingClientRectAsync()!
雪洛's avatar
雪洛 已提交
183
          this.swiperTabsRect.push({
H
hdx 已提交
184 185
            x: rect.left,
            w: rect.width
186
          } as SwiperTabsItem)
H
hdx 已提交
187
        }
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      },
      setSwiperIndex(index : number, updateIndicator : boolean) {
        if (this.swiperIndex === index) {
          return
        }

        this.swiperIndex = index

        this.initSwiperItemData(index)

        if (updateIndicator) {
          this.updateTabIndicator(index, index, 1)
        }
      },
      updateTabIndicator(current_index : number, move_to_index : number, percentage : number) {
雪洛's avatar
雪洛 已提交
203 204
        const current_size = this.swiperTabsRect[current_index]
        const move_to_size = this.swiperTabsRect[move_to_index]
205 206 207 208 209 210

        // 计算指示线 左边距 和 宽度 在移动过程中的线性值
        const indicator_line_x = lerpNumber(current_size.x, move_to_size.x, percentage)
        const indicator_line_w = lerpNumber(current_size.w, move_to_size.w, percentage)

        // 更新指示线
211
        // #ifdef APP
212
        const x = indicator_line_x + indicator_line_w / 2
雪洛's avatar
雪洛 已提交
213
        this.indicatorNode?.style?.setProperty('transform', `translateX(${x}px) scaleX(${indicator_line_w})`)
214
        // #endif
215
        // #ifdef WEB || MP
216 217 218 219 220
        // TODO chrome windows系统 transform scaleX渲染bug
        const x = indicator_line_x
        this.indicatorNode?.style?.setProperty('width', `${indicator_line_w}px`)
        this.indicatorNode?.style?.setProperty('transform', `translateX(${x}px)`)
        // #endif
221 222

        // 滚动到水平中心位置
雪洛's avatar
雪洛 已提交
223
        const scroll_x = x - this.swiperWidth / 2
H
hdx 已提交
224 225 226 227 228 229 230 231 232
        // app 平台后续支持 scrollTo()
        // #ifndef MP-WEIXIN
        this.tabScrollView!.scrollLeft = scroll_x
        // #endif
        // #ifdef MP-WEIXIN
        this.tabScrollView!.scrollTo({
          left: scroll_x
        })
        // #endif
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
      },
      initSwiperItemData(index : number) {
        if (!this.swiperList[index].preload) {
          this.swiperList[index].preload = true;
          (this.$refs["longPage"]! as ComponentPublicInstance[])[index].$callMethod('loadData', null)
        }
      }
    }
  }
</script>

<style>
  .flex-row {
    flex-direction: row;
  }

  .page {
    flex: 1;
  }

  .search-bar {
    padding: 10px;
  }

  .swiper-list {
    height: 100%;
259 260 261
    /* #ifdef WEB */
    flex: 1;
    /* #endif */
262 263 264 265 266 267 268 269 270 271 272
  }

  .swiper-tabs {
    background-color: #ffffff;
    flex-direction: column;
  }

  .swiper-tabs-item {
    color: #555;
    font-size: 16px;
    padding: 12px 25px;
273
    white-space: nowrap;
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  }

  .swiper-tabs-item-active {
    color: #007AFF;
  }

  .swiper-tabs-indicator {
    width: 1px;
    height: 2px;
    background-color: #007AFF;
  }

  .swiper-view {
    flex: 1;
  }

  .swiper-item {
    flex: 1;
  }
</style>