采坑 BS with Element

255 阅读1分钟

今天在完善通过分页组件获取数据的功能时,突然发现分页组件点击下一页会造成当前页数加二,而不是加一,以下便是排除过程。

解决

  • 以为自己代码写错了或者使用了公共变量,多次核查后没问题;
  • 开始怀疑 BS 的锅,通过一个单独分页组件和一个被水平滚动组件包裹的分页组件,多次测试发现被包裹的分页组件才会出现这样的问题;
  • 一直查资料等方式寻求解决方案然而未果,甚至准备提 issue 到 BS ,因为官方仓库说提 issue 要通过 sandbox 搞个示例代码,然后我就把有可能包含错误的代码放上去,一运行结果没什么问题,瞬间懵了加一点点小炸,都准备砍掉分页组件的时候突然有了眉目;
  • 实在无果我就又仔细查看了一下官方文档,发现有提到当两个及以上 BS 嵌套时如果设置了 click: true,那么需要注意加上 stopPropagation: true来阻止事件冒泡,到此成功解决。

官方解释:问题五

代码

HorizontalScroll.vue

<template>
  <div class="h-wrapper" ref="hWrapper">
    <slot></slot>
  </div>
</template>

<script>
// https://better-scroll.github.io/docs/zh-CN/
import BScroll from "better-scroll";
import { throttle } from "@/utils";

export default {
  name: "HorizontalScroll",
  data() {
    return {
      scroll: null,
    };
  },
  props: {
    probeType: {
      type: Number,
      default: 3,
    },
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  mounted() {
    setTimeout(this.__initScroll, 100);
    window.addEventListener("resize", this.refresh);
  },
  methods: {
    __initScroll() {
      // 1.初始化BScroll对象
      if (!this.$refs.hWrapper) return;
      this.scroll = new BScroll(this.$refs.hWrapper, {
        probeType: this.probeType,
        click: true,
        scrollX: true,
        // 阻止冒泡,当页面中存在两个及以上 BS 时会造成两次点击事件
        stopPropagation: true,
      });

      // 2.将监听事件回调
      this.scroll.on(
        "scroll",
        throttle((position) => {
          this.$emit("scroll", position);
        })
      );
    },
    refresh() {
      //  重新计算 BetterScroll,当 DOM 结构发生变化的时候务必要调用确保滚动的效果正常
      this.scroll && this.scroll.refresh && this.scroll.refresh();
    },
    scrollTo(x, y, time) {
      this.scroll && this.scroll.scrollTo && this.scroll.scrollTo(x, y, time);
    },
  },
  beforeDestroy() {
    this.scroll.destroy();
  },
};
</script>

<style scoped>
.h-wrapper {
  display: inline-block;
}
</style>

Item.vue

<horizontal-scroll
  v-show="this.songsFlag"
  class="page-wrapper"
  :probe-type="3"
  ref="page"
>
  <div class="page-content">
    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :total="musiclist.length"
      :current-page="curPage"
      :page-size="pageSize"
      :page-sizes="[15, 25, 30, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
</horizontal-scroll>