我们要实现的是:一个table的滚动条滚动,另一个table的滚动条同时进行滚动
思路:在孙组件MyTable.vue获取当前滚动条数值,以冒泡形式传递给父组件VersionComparison.vue,
父组件获取到数据 然后分发给所有孙子组件MyTable.vue,从而实现所有滚动条同时滚动
如下图所示:
这儿有三层组件:
父组件:VersionComparison.vue
data () {
return {
scrollLeft: 0,
scrollTop: 0,
}
}
methods: {
onScroll(scrollData) {
this.scrollLeft = scrollData.left // 获取到从一个MyTable.vue(孙子组件)传上来的数据
this.scrollTop = scrollData.top // 将获取到的数据分发到各个table中
}
}
子组件:dataTable.vue
props: {
maxHeight: {
type: Number
},
scrollLeft: {
type: Number
},
scrollTop: {
type: Number
}
},
methods: {
onScroll(scrollData) {
this.$emit('onTableScroll', scrollData)
}
}
孙组件:MyTable.vue
props: {
maxHeight: {
default: '100%'
},
scrollLeft: {
type: Number
},
scrollTop: {
type: Number
}
},
watch: {
scrollLeft (newValue) {
this.$refs.elTable.bodyWrapper.scrollLeft = newValue // 获取当前滚动条数值
},
scrollTop (newValue) {
this.$refs.elTable.bodyWrapper.scrollTop = newValue
}
},
mounted() {
this.$refs.elTable.bodyWrapper.addEventListener('scroll', this.onScroll) //监听当前滚动条数值并冒泡到父组件
},
beforeUnMount() {
this.$refs.elTable.bodyWrapper.removeEventListener('scroll', this.onScroll)
},
methods: {
onScroll() {
this.$emit('onTableScroll', {top: this.$refs.elTable.bodyWrapper.scrollTop, left: this.$refs.elTable.bodyWrapper.scrollLeft})
}
}