最近自己从零撸起的甘特图组件需要子组件的滚动条同步滚动
这就涉及到子组件之间的互相通信,通过 消息总线?可以达到我们的需求 ,首先建立一个标志位,拖动左边滚动条的时候,右边的滚动条事件不处理,反之拖动右边滚动条时,左边的滚动条事件不做处理,建立一个公共的变量用于两者的互斥?
store.js
import Vue from 'vue'
export let store = Vue.observable({
scrollFlag: true
})
export let mutations = {
//纵向滚动条同步事件互斥标志位
setScrollFlag(scrollFlag) {
store.scrollFlag = scrollFlag
},
}
建立一个 消息总线的 js 文件?
EventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
左边的滚动组件
<template>
<div ref='taskContent' class="content" @scroll="scroll()" @mouseover="mouseover()">
</div>
</template>
<script>
import { store } from '@/components/gantt/store.js'
import { EventBus } from '../EventBus.js'
import { mutations } from '@/components/gantt/store.js'
export default {
data() {
return {
scrollFlag: true
};
},
watch: {
scrollFlag: function (newVal) {
this.setScrollFlag(newVal)
},
},
mounted() {
EventBus.$on('scroll',(scrollTop) => {
this.$refs.taskContent.scrollTop = scrollTop
})
},
methods: {
setScrollFlag: mutations.setScrollFlag,
scroll() {
if(!this.scrollFlag) {
EventBus.$emit('scroll',this.$refs.taskContent.scrollTop)
}
},
mouseover() {
this.scrollFlag = false
}
}
}
右边的滚动条组件
<template>
<div ref='barContent' @scroll="scroll()" @mouseover="mouseover()">
</div>
</template>
import { store } from '@/components/gantt/store.js'
import { EventBus } from './EventBus.js'
import { mutations } from '@/components/gantt/store.js'
export default {
data() {
return {
scrollFlag: true
}
},
watch: {
scrollFlag: function (newVal) {
this.setScrollFlag(newVal)
},
},
mounted() {
EventBus.$on('scroll',(scrollTop) => {
this.$refs.barContent.scrollTop = scrollTop
})
},
methods: {
setScrollFlag: mutations.setScrollFlag,
scroll() {
if(this.scrollFlag) {
EventBus.$emit('scroll',this.$refs.barContent.scrollTop)
}
},
mouseover() {
this.scrollFlag = true
}
}
}
?以上代码比较好理解,所以没有写什么注释,应该很好懂的
|