项目背景
因为项目较大,有五个界面,每个界面有四个子组件,每个子组件都有一个table表格,需求是每个界面的每个table滚动到顶端表头吸顶,所以尝试用vuex做这种需求。
一、先聊js。
A.首先在vuex可以这样设置。
1.在state文件中设置状态。
techo:{
partsFixed:false,
repairFixed:false,
mateFixed:false,
outRepairFixed:false
}//吸顶状态
2.在action中commit状态。
export const setTecho=function ({commit},data) {
commit(types.UPDATETECHO, {data})
}
3.mutations中更新状态。
[types.UPDATETECHO](state,{data}){
const {name,type} =data;
state.techo[name]=type;
}//更新吸顶状态
B.在界面中我们可以这样操作。
1、因为项目较大,现在main.js中定义全局混合。
Vue.mixin({
methods:{
scrollEvent(name){
if(this.$refs[name]){//this.$refs[name]为表格对象,一定要对表格对象进行判断,因为表格是动态添加的,可能为空,会报错。
let Bottom = this.$refs[name].getBoundingClientRect().bottom,
Top = this.$refs[name].getBoundingClientRect().top,
Height = document.querySelector('.fixedNav').getBoundingClientRect().height;//fixedNav为导航栏
this.$store.dispatch('setTecho',{name,type:Top<=Height && Bottom>=Height})
}
}
}
})
2、在methods中我们可以定义一个回调函数。
partScroll(){
this.scrollEvent('partsFixed')
}
3、在mouted里面进行滚动监听。
mounted(){
window.addEventListener('scroll',this.partScroll);
}
4、最后记得在destroyed里面进行销毁。
destroyed () {
window.removeEventListener('scroll', this.partScroll)
}
二、再聊布局。
1、flex布局模拟table表格。
这样做的好处就是代码量小,position:fixed。应用到flex中,布局不会乱。
2、table布局。
实现方法:复制两个完全一样的table,需要固定定位的table外面包裹div,然后进行定位(table布局进行固定定位布局会乱)。 好处:不需要写太多的样式,坏处:代码量翻倍。
三、讨论
各位有好的方法还可以关注个人微信号(麦坤小子)共同探讨。