在 Vue 2 中实现 el-table
表头在浏览器滚动时吸顶效果
1. 全局注册自定义指令
首先,在 main.js
中全局注册一个自定义指令,用于处理表头的吸顶效果:
// main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
//自定义指令
Vue.directive('sticky', {
inserted(el, binding) {
const elTableHeader = el.querySelector('.el-table__header-wrapper');
const stickyTop = binding.value || 0;
const onScroll = () => {
const scrollTop = window.scrollY || document.documentElement.scrollTop;
const offsetTop = el.getBoundingClientRect().top + scrollTop;
if (scrollTop > offsetTop) {
elTableHeader.style.position = 'fixed';
elTableHeader.style.top = stickyTop + 'px';
elTableHeader.style.zIndex = 1000;
elTableHeader.style.width = el.clientWidth + 'px'; // 防止表头宽度变化
} else {
elTableHeader.style.position = '';
elTableHeader.style.top = '';
elTableHeader.style.zIndex = '';
elTableHeader.style.width = '';
}
};
window.addEventListener('scroll', onScroll);
el._onScroll = onScroll; // 保存引用以便在 unbind 钩子中移除事件监听
},
unbind(el) {
window.removeEventListener('scroll', el._onScroll);
delete el._onScroll;
}
});
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
2. 组件中使用自定义指令
<div class="table-container" v-sticky="0"> //使用自定义指令
<el-table :data="tableData" style="width: 100%" :header-cell-style="tableHeaderCellStyle" :cell-style="tableCellStyle" element-loading-spinner="el-icon-loading" v-loading="loading" >
<el-table-column prop="date" label="达人" show-overflow-tooltip>
<template slot-scope="scope">
<div class="Expert_table_box">
<div class="Expert_url" @click="Viewdetails(scope.row)">
<el-image style="width: 0.8125rem; height: 0.8125rem; border-radius: 50%;" :key="scope.row.uid" :src="scope.row.avatar"></el-image>
</div>
<div class="Expert_table_detail">
<span @click="Viewdetails(scope.row)" style="font-size: 0.1875rem; color: black">{{ scope.row.nickname }}</span>
<span style="font-size: 0.15rem">{{ scope.row.douyinId }}  <i class="el-icon-copy-document" @click="copySpuId(scope.row.douyinId)"></i></span>
</div>
</div>
</template>
</el-table-column>
<el-table-column prop="mplatformFollowersCount" label="粉丝数" sortable></el-table-column>
<el-table-column prop="addFansCount" label="新增粉丝" sortable></el-table-column>
<el-table-column prop="addAwemeCount" label="新增视频数" sortable></el-table-column>
<el-table-column prop="awemeCount" label="视频总数" sortable></el-table-column>
<el-table-column prop="totalFavorited" label="点赞数" sortable></el-table-column>
</el-table>
</div>