index.vue 18.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

<script>
import touchtrack from 'uni-mixins/touchtrack'

export default {
  name: 'Swiper',
  mixins: [touchtrack],
  props: {
    indicatorDots: {
      type: [Boolean, String],
      default: false
    },
    vertical: {
      type: [Boolean, String],
      default: false
    },
    autoplay: {
      type: [Boolean, String],
      default: false
    },
    circular: {
      type: [Boolean, String],
      default: false
    },
    interval: {
      type: [Number, String],
      default: 5e3
    },
    duration: {
      type: [Number, String],
      default: 500
    },
    current: {
      type: [Number, String],
      default: 0
    },
    indicatorColor: {
      type: String,
      default: ''
    },
    indicatorActiveColor: {
      type: String,
      default: ''
    },
    previousMargin: {
      type: String,
      default: ''
    },
    nextMargin: {
      type: String,
      default: ''
    },
    currentItemId: {
      type: String,
      default: ''
    },
    skipHiddenItemLayout: {
      type: [Boolean, String],
      default: false
    },
    displayMultipleItems: {
      type: [Number, String],
      default: 1
    }
  },
  data () {
    return {
      currentSync: Math.round(this.current) || 0,
      currentItemIdSync: this.currentItemId || '',
      userTracking: false,
      currentChangeSource: '',
      items: [],
      itemIdItemMap: {}
    }
  },
  computed: {
    intervalNumber () {
      const interval = Number(this.interval)
      return isNaN(interval) ? 5e3 : interval
    },
    durationNumber () {
      const duration = Number(this.duration)
      return isNaN(duration) ? 500 : duration
    },
    displayMultipleItemsNumber () {
      const displayMultipleItems = Math.round(this.displayMultipleItems)
      return isNaN(displayMultipleItems) ? 1 : displayMultipleItems
    },
    slidesStyle () {
      var style = {}
      if (this.nextMargin || this.nextMargin) {
        style = this.vertical ? {
          left: 0,
          right: 0,
          top: this._upx2px(this.previousMargin),
          bottom: this._upx2px(this.nextMargin)
        } : {
          top: 0,
          bottom: 0,
          left: this._upx2px(this.previousMargin),
          right: this._upx2px(this.nextMargin)
        }
      }
      style.width = this.vertical ? '100%' : Math.abs(100 / this.displayMultipleItemsNumber) + '%'
      style.height = !this.vertical ? '100%' : Math.abs(100 / this.displayMultipleItemsNumber) + '%'
      return style
    },
    circularEnabled () {
      return this.circular && this.items.length > this.displayMultipleItemsNumber
    }
  },
  watch: {
    vertical () {
      this._resetLayout()
    },
    circular () {
      this._resetLayout()
    },
    intervalNumber (val) {
      if (this._timer) {
        this._cancelSchedule()
        this._scheduleAutoplay()
      }
    },
    current (val) {
      this._currentCheck()
    },
    currentSync (val) {
      this._currentChanged(val)
      this.$emit('update:current', val)
    },
    currentItemId (val) {
      this._currentCheck()
    },
    currentItemIdSync (val) {
      this.$emit('update:currentItemId', val)
    },
    displayMultipleItemsNumber () {
      this._resetLayout()
    }
    // itemIdItemMap () {
    //   this._resetLayout()
    // }
  },
  created () {
    this._invalid = true
    this._viewportPosition = 0
    this._viewportMoveRatio = 1
    this._animating = null
    this._requestedAnimation = false
    this._userDirectionChecked = false
    this._contentTrackViewport = 0
    this._contentTrackSpeed = 0
    this._contentTrackT = 0
  },
  mounted () {
    this._currentCheck()
    this.touchtrack(this.$refs.slidesWrapper, '_handleContentTrack', true)
    this._resetLayout()
    this.$watch(() => {
      return this.autoplay && !this.userTracking
    }, this._inintAutoplay)
    this._inintAutoplay(this.autoplay && !this.userTracking)
    this.$watch('items.length', this._resetLayout)
  },
  beforeDestroy () {
    this._cancelSchedule()
  },
  methods: {
    _itemIdUpdated (item, val, oldVal) {
      if (oldVal) {
        this.$set(this.itemIdItemMap, oldVal, null)
      }
      if (val) {
        this.$set(this.itemIdItemMap, val, item.$vnode)
      }
    },
    _inintAutoplay (enable) {
      if (enable) {
        this._scheduleAutoplay()
      } else {
        this._cancelSchedule()
      }
    },
    /**
     * 页面变更检查和同步
     */
    _currentCheck () {
      var current = this.items.indexOf(this.itemIdItemMap[this.currentItemId])
      if (current < 0) {
        current = Math.round(this.current) || 0
      }
      current = current < 0 ? 0 : current
      this.currentSync = current
    },
    _itemReady (vnode, callback) {
      if (vnode.componentInstance && vnode.componentInstance._isMounted) {
        callback()
      } else {
        vnode._callbacks = vnode._callbacks || []
        vnode._callbacks.push(callback)
      }
    },
    /**
     * 当前页面变更
     */
    _currentChanged (current) {
      var source = this.currentChangeSource
      this.currentChangeSource = ''
      if (!source) {
        this._animateViewport(current, '', 0)
      }
      var item = this.items[current]
      if (item) {
        this._itemReady(item, () => {
          var currentItemId = this.currentItemIdSync = item.componentInstance.itemId || ''
          this.$trigger('change', {}, {
            current: this.currentSync,
            currentItemId,
            source
          })
        })
      }
    },
    /**
     * 自动播放
     */
    _scheduleAutoplay () {
      var self = this
      this._cancelSchedule()
      function timer () {
        self._timer = null
        self.currentChangeSource = 'autoplay'
        if (self.circularEnabled) {
          self.currentSync = self._normalizeCurrentValue(self.currentSync + 1)
        } else {
          self.currentSync = self.currentSync + self.displayMultipleItemsNumber < self.items.length ? self.currentSync + 1 : 0
        }
        self._animateViewport(self.currentSync, 'autoplay', self.circularEnabled ? 1 : 0)
        self._timer = setTimeout(timer, self.intervalNumber)
      }
      if (!(!this._isMounted || this._invalid || this.items.length <= this.displayMultipleItemsNumber)) {
        this._timer = setTimeout(timer, this.intervalNumber)
      }
    },
    /**
     * 清除定时器
     */
    _cancelSchedule () {
      if (this._timer) {
        clearTimeout(this._timer)
        this._timer = null
      }
    },
    /**
     * 检查当前页值
     */
    _normalizeCurrentValue (current) {
      var length = this.items.length
      if (!length) {
        return -1
      }
      var index = (Math.round(current) % length + length) % length
      if (this.circularEnabled) {
        if (length <= this.displayMultipleItemsNumber) {
          return 0
        }
      } else if (index > length - this.displayMultipleItemsNumber) {
        return length - this.displayMultipleItemsNumber
      }
      return index
    },
    _upx2px (val) {
      if (/\d+[ur]px$/i.test(val)) {
        val.replace(/\d+[ur]px$/i, text => {
          return `${uni.upx2px(parseFloat(text))}px`
        })
      }
      return val || ''
    },
    /**
     * 重新布局
     */
    _resetLayout () {
      if (this._isMounted) {
        this._cancelSchedule()
        this._endViewportAnimation()
        var items = this.items

        for (var i = 0; i < items.length; i++) {
          this._updateItemPos(i, i)
        }
        this._viewportMoveRatio = 1
        if (this.displayMultipleItemsNumber === 1 && items.length) {
          var itemRect = items[0].componentInstance.$el.getBoundingClientRect()
          var slideFrameRect = this.$refs.slideFrame.getBoundingClientRect()
          this._viewportMoveRatio = itemRect.width / slideFrameRect.width
          if (!(this._viewportMoveRatio > 0 && this._viewportMoveRatio < 1)) {
            this._viewportMoveRatio = 1
          }
        }
        var position = this._viewportPosition
        this._viewportPosition = -2
        var current = this.currentSync
        if (current >= 0) {
          this._invalid = false
          if (this.userTracking) {
            this._updateViewport(position + current - this._contentTrackViewport)
            this._contentTrackViewport = current
          } else {
            this._updateViewport(current)
          }
        } else {
          this._invalid = true
          this._updateViewport(-this.displayMultipleItemsNumber - 1)
        }
      }
    },
    _checkCircularLayout (e) {
      if (!this._invalid) {
        for (var items = this.items, n = items.length, i = e + this.displayMultipleItemsNumber, r = 0; r < n; r++) {
          var item = items[r]
          var _position = item._position
          var s = Math.floor(e / n) * n + r
          var l = s + n
          var c = s - n
          var u = Math.max(e - (s + 1), s - i, 0)
          var d = Math.max(e - (l + 1), l - i, 0)
          var h = Math.max(e - (c + 1), c - i, 0)
          var p = Math.min(u, d, h)
          var f = [s, l, c][[u, d, h].indexOf(p)]
          if (_position !== f) {
            this._updateItemPos(r, f)
          }
        }
      }
    },
    _updateItemPos (current, position) {
      var n = this.vertical ? '0' : 100 * position + '%'
      var i = this.vertical ? 100 * position + '%' : '0'
      var transform = 'translate(' + n + ', ' + i + ') translateZ(0)'
      var item = this.items[current]
      this._itemReady(item, () => {
        var el = item.componentInstance.$el
        el.style['-webkit-transform'] = transform
        el.style.transform = transform
        el._position = position
      })
    },
    _updateViewport (index) {
      if (!(Math.floor(2 * this._viewportPosition) === Math.floor(2 * index) && Math.ceil(2 * this._viewportPosition) === Math.ceil(2 * index))) {
        if (this.circularEnabled) {
          this._checkCircularLayout(index)
        }
        if (this.skipHiddenItemLayout) {
          this._updateHiddenItemDisplay(index)
        }
      }

      var t = this.vertical ? '0' : 100 * -index * this._viewportMoveRatio + '%'
      var n = this.vertical ? 100 * -index * this._viewportMoveRatio + '%' : '0'
      var i = 'translate(' + t + ', ' + n + ') translateZ(0)'
      var slideFrame = this.$refs.slideFrame
      if (slideFrame) {
        slideFrame.style['-webkit-transform'] = i
        slideFrame.style.transform = i
      }
      this._viewportPosition = index
    },
    _animateFrameFuncProto () {
      if (!this._animating) {
        this._requestedAnimation = false
        return
      }
      var _animating = this._animating
      var toPos = _animating.toPos
      var acc = _animating.acc
      var endTime = _animating.endTime
      var source = _animating.source
      var time = endTime - Date.now()
      if (time <= 0) {
        this._updateViewport(toPos)
        this._animating = null
        this._requestedAnimation = false
        var item = this.items[this.currentSync]
        if (item) {
          this._itemReady(item, () => {
            var currentItemId = item.componentInstance.itemId || ''
            this.$trigger('animationfinish', {}, {
              current: this.currentSync,
              currentItemId,
              source
            })
          })
        }
        return
      }
      var s = acc * time * time / 2
      var l = toPos + s
      this._updateViewport(l)
      requestAnimationFrame(this._animateFrameFuncProto.bind(this))
    },
    _animateViewport (current, source, n) {
      this._cancelViewportAnimation()
      var duration = this.durationNumber
      var length = this.items.length
      var position = this._viewportPosition
      if (this.circularEnabled) {
        if (n < 0) {
          for (; position < current;) {
            position += length
          }
          for (; position - length > current;) {
            position -= length
          }
        } else if (n > 0) {
          for (; position > current;) {
            position -= length
          }
          for (; position + length < current;) {
            position += length
          }
        } else {
          for (; position + length < current;) {
            position += length
          }
          for (; position - length > current;) {
            position -= length
          }
          if (position + length - current < current - position) {
            position += length
          }
        }
      }

      this._animating = {
        toPos: current,
        acc: 2 * (position - current) / (duration * duration),
        endTime: Date.now() + duration,
        source: source
      }
      if (!this._requestedAnimation) {
        this._requestedAnimation = true
        requestAnimationFrame(this._animateFrameFuncProto.bind(this))
      }
    },
    _cancelViewportAnimation () {
      this._animating = null
    },
    /**
     * 结束动画
     */
    _endViewportAnimation () {
      if (this._animating) {
        this._updateViewport(this._animating.toPos)
        this._animating = null
      }
    },
    _handleTrackStart () {
      this._cancelSchedule()
      this._contentTrackViewport = this._viewportPosition
      this._contentTrackSpeed = 0
      this._contentTrackT = Date.now()
      this._cancelViewportAnimation()
    },
    _handleTrackMove (data) {
      var self = this
      var contentTrackT = this._contentTrackT
      this._contentTrackT = Date.now()
      var length = this.items.length
      var other = length - this.displayMultipleItemsNumber
      function calc (val) {
        return 0.5 - 0.25 / (val + 0.5)
      }

      function move (oldVal, newVal) {
        var val = self._contentTrackViewport + oldVal
        self._contentTrackSpeed = 0.6 * self._contentTrackSpeed + 0.4 * newVal
        if (!self.circularEnabled) {
          if (val < 0 || val > other) {
            if (val < 0) {
              val = -calc(-val)
            } else {
              if (val > other) {
                val = other + calc(val - other)
              }
            }
            self._contentTrackSpeed = 0
          }
        }
        self._updateViewport(val)
      }
      if (this.vertical) {
        move(-data.dy / this.$refs.slideFrame.offsetHeight, -data.ddy / (this._contentTrackT - contentTrackT))
      } else {
        move(-data.dx / this.$refs.slideFrame.offsetWidth, -data.ddx / (this._contentTrackT - contentTrackT))
      }
    },
    _handleTrackEnd (isCancel) {
      this.userTracking = false
      var t = this._contentTrackSpeed / Math.abs(this._contentTrackSpeed)
      var n = 0
      if (!isCancel && Math.abs(this._contentTrackSpeed) > 0.2) {
        n = 0.5 * t
      }
      var current = this._normalizeCurrentValue(this._viewportPosition + n)
      if (isCancel) {
        this._updateViewport(this._contentTrackViewport)
      } else {
        this.currentChangeSource = 'touch'
        this.currentSync = current
        this._animateViewport(current, 'touch', n !== 0 ? n : current === 0 && (this.circularEnabled && this._viewportPosition >= 1) ? 1 : 0)
      }
    },
    _handleContentTrack (e) {
      if (!this._invalid) {
        if (e.detail.state === 'start') {
          this.userTracking = true
          this._userDirectionChecked = !1
          return this._handleTrackStart()
        }
        // fixed by xxxxxx
        if (e.detail.state === 'end') {
          return this._handleTrackEnd(false)
        }
        if (e.detail.state === 'cancel') {
          return this._handleTrackEnd(true)
        }
        if (this.userTracking) {
          if (!this._userDirectionChecked) {
            this._userDirectionChecked = true
            var t = Math.abs(e.detail.dx)
            var n = Math.abs(e.detail.dy)
            if (t >= n && this.vertical) {
              this.userTracking = false
            } else {
              if (t <= n && !this.vertical) {
                this.userTracking = false
              }
            }
            if (!this.userTracking) {
              return
            }
          }
          this._handleTrackMove(e.detail)
          return false
        }
      }
    }
  },
  render (createElement) {
    var slidesDots = []
    var index = 0
    var swiperItems = []
    this.$slots.default.forEach(vnode => {
      if (vnode.componentOptions && vnode.componentOptions.tag === 'v-uni-swiper-item') {
        swiperItems.push(vnode)
        slidesDots.push(createElement('div', {
          class: {
            'uni-swiper-dot': true,
            'uni-swiper-dot-active': index === this.currentSync
          },
          style: {
            'background': index === this.currentSync ? this.indicatorActiveColor : this.indicatorColor
          }
        }))
        index++
      }
    })
    this.items = swiperItems
    var slidesWrapperChild = [createElement('div', {
      ref: 'slides',
      style: this.slidesStyle,
      'class': 'uni-swiper-slides'
    }, [
      createElement('div', {
        ref: 'slideFrame',
        class: 'uni-swiper-slide-frame'
      }, swiperItems)
    ])]
    if (this.indicatorDots) {
      slidesWrapperChild.push(createElement('div', {
        ref: 'slidesDots',
        'class': ['uni-swiper-dots', this.vertical ? 'uni-swiper-dots-vertical' : 'uni-swiper-dots-horizontal']
      }, slidesDots))
    }

    return createElement(
      'uni-swiper',
      [createElement('div', {
        ref: 'slidesWrapper',
        'class': 'uni-swiper-wrapper',
        on: this.$listeners
      }, slidesWrapperChild)]
    )
  }
}
</script>
<style>
uni-swiper {
  display: block;
  height: 150px;
}

uni-swiper[hidden] {
  display: none;
}

uni-swiper .uni-swiper-wrapper {
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}

uni-swiper .uni-swiper-slides {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

uni-swiper .uni-swiper-slide-frame {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  will-change: transform;
}

uni-swiper .uni-swiper-dots {
  position: absolute;
  font-size: 0;
}

uni-swiper .uni-swiper-dots-horizontal {
  left: 50%;
  bottom: 10px;
  text-align: center;
  white-space: nowrap;
  -webkit-transform: translate(-50%, 0);
  transform: translate(-50%, 0);
}

uni-swiper .uni-swiper-dots-horizontal .uni-swiper-dot {
  margin-right: 8px;
}

uni-swiper .uni-swiper-dots-horizontal .uni-swiper-dot:last-child {
  margin-right: 0;
}

uni-swiper .uni-swiper-dots-vertical {
  right: 10px;
  top: 50%;
  text-align: right;
  -webkit-transform: translate(0, -50%);
  transform: translate(0, -50%);
}

uni-swiper .uni-swiper-dots-vertical .uni-swiper-dot {
  display: block;
  margin-bottom: 9px;
}

uni-swiper .uni-swiper-dots-vertical .uni-swiper-dot:last-child {
  margin-bottom: 0;
}

uni-swiper .uni-swiper-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  cursor: pointer;
  transition-property: background-color;
  transition-timing-function: ease;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
}

uni-swiper .uni-swiper-dot-active {
  background-color: #000000;
}
</style>