JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue滚动事件爬坑记

2019. 11. 12    

Vue滚动事件爬坑记

需求:

vue里面table拉到下面,不到表头,需要把表头固定在窗口

用的是iview UI组件库

//挂载滚动事件
mounted() {
  window.addEventListener("scroll", this.tableScroll, true);
},
methods: {

tableScroll(e) {
  //获取表头容器父级 用于获取表距离顶部高度
  let tableBox = document.getElementById("tableBox"); 
  if(tableBox){ // 当这个表没有数据的时候,不走这里,否则会报错
    //获取整个表的大容器。用于当表fiexd 定位,整个表高度会变小,
    //如果这时这正好滚动条这里个临界点,会出现抖动,
    let tabledefault = document.getElementsByClassName("ivu-table-default")[0];
    //获取表头容器,用于添加/删除定位的class
    let theadBox = document.getElementsByClassName("ivu-table-header")[0];
    let tableScrollTop = tableBox.offsetTop;
    if (e.target.scrollTop > tableScrollTop) {
      theadBox.classList.add("Tablefiexd");
      //在表头fiexd时 ,大容器的padding-top + 表头的高度
      tabledefault.classList.add("paddingAdd");
    } else {
      theadBox.classList.remove("Tablefiexd");
      tabledefault.classList.remove("paddingAdd");
    }
  }else{
     return false
  }
},

},
//卸载滚动事件
destroyed(){
  window.removeEventListener('scroll', this.tableScroll,true);
},

router 配置

重点

router.afterEach((to, from, next) => {;
  window.scrollTo(0,0);
  Promise.resolve()
    .then(()=>{
      url: global.location.href
    })
});