Vue的mixin的一点使用(table的头部sticky的实现)

大家对mixin应该熟悉,它能全局或者配置mixin的组件添加公共属性与方法。这里展示一次具体的使用。

在使用element-ui时(别的场景一样出现),table过长时滚动时,头部滚出视图了,就无法知道下面内容每一列代表啥。这里的实现方案采用sticky即可,即滚出视图让列表的头部固定在顶部。

这里采用mixin来实现,需要的页面配置mixin即可,代码如下

// 引入计算偏移的方法和节流方法
import OffsetManage from '@flyme/utils/lib/domUtils/OffsetManage'
import throttle from '@flyme/utils/lib/helper/throttle'
 
 
const tableHeaderFixMixin = {
  mounted() {
    // SPA页面使用了vue-router
    this.routerViewEl = document.querySelector('.main-router-view')
    if (this.routerViewEl) {
      // 节流
      this.scrollFn = throttle(() => {
        // 滚出添加fixed样式,否则去除
        if (this.tableHeader) {
          const top = parseInt(this.tableHeader.dataset.top)
          if (this.routerViewEl.scrollTop > top) {
            this.tableHeader.classList.add('fixed-table-header')
            this.tableHeader.style.width = this.tableHeader.parentNode.offsetWidth + 'px'
          } else {
            this.tableHeader.classList.remove('fixed-table-header')
            this.tableHeader.style.width = '100%'
          }
        }
      }, 90)
      this.routerViewEl.addEventListener('scroll', this.scrollFn)
      this.$nextTick(() => {
        this.initStickyTableHeader()
      })
    }
 
  },
 
  beforeDestroy() {
    // 记得销毁
    this.routerViewEl.removeEventListener('scroll', this.scrollFn)
  },
 
  methods: {
    // 初始化datatable的header的sticky
    initStickyTableHeader() {
      this.tableHeader = document.querySelector('.el-table__header-wrapper')
      if (this.tableHeader) {
        this.tableHeader.dataset.top = OffsetManage.top(this.tableHeader)
      }
    },
  },
}
 
export { tableHeaderFixMixin 

具体使用

import { tableHeaderFixMixin } from '../mixins'
 
export default {
  ...
  mixins: [tableHeaderFixMixin],
  ...

转载于:https://juejin.im/post/5b97a43bf265da0ac9628639

posted @ 2020-02-04 13:33  catgatp  阅读(894)  评论(0编辑  收藏  举报