zoukankan      html  css  js  c++  java
  • vue无缝滚动的插件开发填坑分享

    写插件的初衷

    1.项目经常需要无缝滚动效果,当时写jq的时候用用msClass这个老插件,相对不上很好用。

    2.后来转向vue在vue-awesome没有找到好的无缝滚动插件,除了配置swiper可以实现但是相对来说太重了,于是自己造了个轮子。

    3.在这分享下,当时写这个插件的坑,自己也复习下,如果代码上有瑕疵欢迎指出。

    源码参考 vue-seamless-scroll

    1.简单的实现上下滚动基本版(最初版)

    html

    1.solt提供默认插槽位来放置父组件传入的html

    ```<template> <div @mouseenter="enter" @mouseleave="leave"> <div ref="wrapper" :style="pos"> <slot></slot> </div> </div> </template> ```
    javascript

    1.animationFrame 动画api兼容处理

    2.arrayEqual 判断数组是否相等 来监听data的变化来实现更新无缝滚动

    
    &lt;script&gt;
    
      require('comutils/animationFrame')  //requestAnimationFrame api
      const arrayEqual = require('comutils/arrayEqual')
      export default {
        data () {
          return {
            yPos: 0,
            reqFrame: null
          }
        },
        props: {
          data: { // data 数据
            type: Array,
            default: []
          },
          classOption: { //参数
            type: Object,
            default: {}
          }
        },
        computed: {
          pos () {
            // 给父元素的style
            return {transform: `translate(0,${this.yPos}px)`}
          },
          defaultOption () {
            return {
              step: 1, //步长
              limitMoveNum: 5, //启动无缝滚动最小数据数
              hoverStop: true, //是否启用鼠标hover控制
              direction: 1 //1 往上 0 往下
            }
          },
          options () {
            // 合并参数
            return Object.assign({}, this.defaultOption, this.classOption)
          }
          ,
          moveSwitch () {
          //判断传入的初始滚动值和data的length来控制是否滚动
            return this.data.length &lt; this.options.limitMoveNum
          }
        },
        methods: {
          enter () {
            if (!this.options.hoverStop || this.moveSwitch) return
            cancelAnimationFrame(this.reqFrame)
          },
          leave () {
            if (!this.options.hoverStop || this.moveSwitch) return
            this._move()
          },
          _move () {
            //滚动
            this.reqFrame = requestAnimationFrame(
              () =&gt; {
                let h = this.$refs.wrapper.offsetHeight / 2
                let direction = this.options.direction
                if (direction === 1) {
                  if (Math.abs(this.yPos) &gt;= h) this.yPos = 0
                } else {
                  if (this.yPos &gt;= 0) this.yPos = h * -1
                }
                if (direction === 1) {
                  this.yPos -= this.options.step
                } else {
                  this.yPos += this.options.step
                }
                this._move()
              }
            )
          },
          _initMove () {
            if (this.moveSwitch) {
              cancelAnimationFrame(this.reqFrame)
              this.yPos = 0
            } else {
              this.$emit('copyData') //需要copy复制一份 emit到父元素  后期版本这里已经优化
              if (this.options.direction !== 1) {
                setTimeout(() =&gt; {
                  this.yPos = this.$refs.wrapper.offsetHeight / 2 * -1
                }, 20)
              }
              this._move()
            }
          }
        },
        mounted () {
          this._initMove()
        },
        watch: {
          //监听data的变化
          data (newData, oldData) {
            if (!arrayEqual(newData, oldData.concat(oldData))) {
              cancelAnimationFrame(this.reqFrame)
              this._initMove()
            }
          }
        }
      }
    &lt;/script&gt;
    

    1.1 优化1: 新增配置openWatch 是否开启data监控实时刷新

    有兴趣可以看本次commit记录 myClass.vue的更改

    1.2 优化2: 新增配置singleHeight waitTime参数 控制是否单步滚动

    commit记录

    1.3 优化3:添加对移动端touch事件滚动列表支持

    commit记录

    1.4 优化4: 去掉了emit回调(简化初始化)

    
    //原本组件调用
    &lt;my-class :data="listData" :class-option="classOption" @copy-data="listData = listData.concat(listData)"&gt;
    //简化后组件调用
    &lt;my-class :data="listData" :class-option="classOption" class="warp"&gt;
    
    
    用js的来复制一份innerHtml来代替之前的做法简化使用
    //this.$emit('copyData')
    
     timer = setTimeout(() =&gt; { //20ms延迟 作用保证能取到最新的html
       this.copyHtml = this.$refs.slotList.innerHTML
     }, 20)
     // template
     &lt;template&gt;
        &lt;div @mouseenter="enter" @mouseleave="leave" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"&gt;
            &lt;div ref="wrap" :style="pos"&gt;
                &lt;div ref="slotList" :style="float"&gt;
                    &lt;slot&gt;&lt;/slot&gt;
                &lt;/div&gt;
                &lt;div v-html="copyHtml" :style="float"&gt;&lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/template&gt;
    

    commit记录

    1.5 bug1: 解决ie9下animationFrame报错的bug

    这个问题的原因查了比较久最后发现是当时没有加return没有取到定时器id

    ![](https://img2018.cnblogs.com/blog/1504257/201811/1504257-20181113142133648-879443480.png)

    1.6 优化5:添加左右无缝滚动

    类似上下可以查看commit

    1.7 Vue.use() 提供install全局注册

    
    import vueMyCLass from './components/myClass.vue'
    
    let myScroll
    
    const defaultComponentName = 'vue-seamless-scroll'
    
    // expose component to global scope
    if (typeof window !== 'undefined' &amp;&amp; window.Vue) {
      Vue.component('vue-seamless-scroll', vueMyCLass)
    } else {
      myScroll = {
        install: function (Vue, options = {}) {
          Vue.component(options.componentName || defaultComponentName, vueMyCLass)
        }
      }
    
    }
    
    export default myScroll
    

    1.8 bug 解决了touchMove频繁快速操作导致单步滚动失效bug 和部分代码优化

    //1.封装多次调用的取消动画方法

    
    _cancle: function _cancle() {
         cancelAnimationFrame(this.reqFrame || '');
        },
    

    //2.touchMove频繁快速操作导致滚动错乱bug

    
     _move () {
        this._cancle() //进入move立即先清除动画 防止频繁touchMove导致多动画同时进行
        }    
    

    //3.生命周期结束前取消动画

    
     beforeDestroy () {
          this._cancle()
    }
    

    //4.修复不传参数报警告的bug

    
     props: {
          data: {
            type: Array,
            default: () =&gt; {
              return []
            }
          },
          classOption: {
            type: Object,
            default: () =&gt; {
              return {}
            }
          }
        }
    

    //5.Fixing a bug. add a overflow:hidden on the child element

    部分人喜欢用margin-top如果没有overflow等限制会导致我里面计算高度和实际有些许差距导致最后效果到临界位置有轻微抖动
    //默认加上了overflow: 'hidden'
    
    computed: {
          float () {
            return this.options.direction &gt; 1 ? {float: 'left', overflow: 'hidden'} : {overflow: 'hidden'}
          },
          pos () {
            return {
              transform: `translate(${this.xPos}px,${this.yPos}px)`,
              transition: `all ease-in ${this.delay}ms`,
              overflow: 'hidden'
            }
          }
    }
    

    //6.新增单步滚动也能hover停止的功能

    之前因为单步滚动内置了延迟执行this._move()默认单步限制了鼠标悬停停止无缝滚动,后来通过给this._move()加上开关达到效果。

    commit

    TKS

    如果对原生js实现类似的无缝滚动有兴趣可以留言,我抽空也可以写下seamless-scroll

    vue-seamless-scroll发现bug或者有什么不足望指点,感觉不错点个star吧。

    原文地址:https://segmentfault.com/a/1190000013010808

  • 相关阅读:
    kafka学习-卡不卡的简单使用
    mongoDB-mongo compass使用学习-最像关系型数据库的非关系型文档型数据库
    postman使用-跑男常用功能
    jmeter数据驱动csv+批量导出数据到csv文件
    jmeter-数据库查询与调用-mysql
    arch linux mysql using
    Win10安装 oracle11g 出现INS-13001环境不满足最低要求解决方法
    oracle11g数据库安装
    安装PLSQLDeveloper
    oracle基本学习
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9951954.html
Copyright © 2011-2022 走看看