index.vue 2.3 KB
Newer Older
P
Pan 已提交
1
<template>
2 3 4
  <el-scrollbar ref="scrollContainer" :vertical="false" class="scroll-container" @wheel.native.prevent="handleScroll">
    <slot/>
  </el-scrollbar>
P
Pan 已提交
5 6 7
</template>

<script>
8
const tagAndTagSpacing = 4 // tagAndTagSpacing
P
Pan 已提交
9

P
Pan 已提交
10
export default {
11
  name: 'ScrollPane',
P
Pan 已提交
12 13 14 15 16 17 18
  data() {
    return {
      left: 0
    }
  },
  methods: {
    handleScroll(e) {
19 20 21
      const eventDelta = e.wheelDelta || -e.deltaY * 40
      const $scrollWrapper = this.$refs.scrollContainer.$refs.wrap
      $scrollWrapper.scrollLeft = $scrollWrapper.scrollLeft + eventDelta / 4
P
Pan 已提交
22
    },
23
    moveToTarget(currentTag) {
24
      const $container = this.$refs.scrollContainer.$el
P
Pan 已提交
25
      const $containerWidth = $container.offsetWidth
26
      const $scrollWrapper = this.$refs.scrollContainer.$refs.wrap
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
      const tagList = this.$parent.$refs.tag

      let firstTag = null
      let lastTag = null

      // find first tag and last tag
      if (tagList.length > 0) {
        firstTag = tagList[0]
        lastTag = tagList[tagList.length - 1]
      }

      if (firstTag === currentTag) {
        $scrollWrapper.scrollLeft = 0
      } else if (lastTag === currentTag) {
        $scrollWrapper.scrollLeft = $scrollWrapper.scrollWidth - $containerWidth
42
      } else {
43 44 45 46
        // find preTag and nextTag
        const currentIndex = tagList.findIndex(item => item === currentTag)
        const prevTag = tagList[currentIndex - 1]
        const nextTag = tagList[currentIndex + 1]
47 48 49 50 51 52 53 54 55 56 57
        // the tag's offsetLeft after of nextTag
        const afterNextTagOffsetLeft = nextTag.$el.offsetLeft + nextTag.$el.offsetWidth + tagAndTagSpacing

        // the tag's offsetLeft before of prevTag
        const beforePrevTagOffsetLeft = prevTag.$el.offsetLeft - tagAndTagSpacing

        if (afterNextTagOffsetLeft > $scrollWrapper.scrollLeft + $containerWidth) {
          $scrollWrapper.scrollLeft = afterNextTagOffsetLeft - $containerWidth
        } else if (beforePrevTagOffsetLeft < $scrollWrapper.scrollLeft) {
          $scrollWrapper.scrollLeft = beforePrevTagOffsetLeft
        }
P
Pan 已提交
58
      }
P
Pan 已提交
59 60 61 62 63 64 65 66 67
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.scroll-container {
  white-space: nowrap;
  position: relative;
P
Pan 已提交
68
  overflow: hidden;
69
  width: 100%;
70 71 72 73 74 75 76
  /deep/ {
    .el-scrollbar__bar {
      bottom: 0px;
    }
    .el-scrollbar__wrap {
      height: 49px;
    }
P
Pan 已提交
77 78 79
  }
}
</style>