# 首页
# 技术点
swiper 图片相似的背景色 throttle 函数使用 scroll 事件 事件绑定与注销
# 轮播
轮播组件主要使用 swiper 插件实现,特别处在于图片变更时,背景颜色也会跟随变更。
实现原理是轮播图变更时,会触发 slideChange ,该方法会返回当前滚动图片的索引值。
根据返回的索引,设置对应的背景色。该背景色为当前图片的平均色调,由七牛云存储提供的方法获取。
# 主要代码
# 轮播实例
// 实例化轮播插件
let _this = this; // vue 的 this
new Swiper(".home-swiper", {
  loop: true,
  speed: 600,
  autoplay: {
    delay: 3000,
    stopOnLastSlide: false,
    disableOnInteraction: true,
  },
  on: {
    slideChange: function () {
      // _this 上面定义指向 vue 实例
      // this 指向 swiper 的实例
      // this.activeIndex 为当前显示的图片索引
      _this.$emit("swiper-index-change", this.activeIndex - 1);
    },
  },
});
# 变更背景色
// 根据轮播变换背景色(swiper的index有bug)
onSwiperIndexChange(index = 0) {
  const len = this.swipers.length;
  // swiper 的最后一张图片索引与真实索引对应有bug,此处处理下
  if (len) {
    if (index === len) {
      index = 0;
    } else if (index < 0) {
      index = len - 1;
    }
    // 设置背景色
    this.bgcolor = this.swipers[index].bgcolor;
  }
},
# 头部
头部组件主要使用滚动事件监听,变更头部背景色,以及滚动节流方法的使用
主要代码
activated() {
  window.addEventListener("scroll", this.getScrollTop);
},
deactivated() {
  window.removeEventListener("scroll", this.getScrollTop);
},
methods: {
  // 滚动节流
  handleScroll: throttle(function () {
    this.getScrollTop();
  }),
  getScrollTop() {
    // document.documentElement.scrollTop 声明DTD
    // document.body.scrollTop  未声明DTD
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    this.scrollTop = scrollTop;
  },
},
# 卡片式内容
主要使用 MPanel 组件,其 scroll-x 属性控制是否开启横向滚动