vue实现左右联动
Vue 实现左右联动效果
左右联动通常指两个独立滚动的容器(如列表)在滚动时保持同步。以下是实现方案:
监听滚动事件
在左右两个容器上绑定 scroll 事件,通过事件处理函数实现同步滚动。需注意避免事件循环触发。

<template>
<div class="container">
<div class="left-list" ref="leftList" @scroll="handleLeftScroll">
<!-- 左侧内容 -->
</div>
<div class="right-list" ref="rightList" @scroll="handleRightScroll">
<!-- 右侧内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
isScrolling: false
}
},
methods: {
handleLeftScroll() {
if (this.isScrolling) return;
this.isScrolling = true;
const leftScrollTop = this.$refs.leftList.scrollTop;
this.$refs.rightList.scrollTop = leftScrollTop;
setTimeout(() => {
this.isScrolling = false;
}, 100);
},
handleRightScroll() {
if (this.isScrolling) return;
this.isScrolling = true;
const rightScrollTop = this.$refs.rightList.scrollTop;
this.$refs.leftList.scrollTop = rightScrollTop;
setTimeout(() => {
this.isScrolling = false;
}, 100);
}
}
}
</script>
使用 CSS 同步高度
确保左右容器高度一致,滚动条才会同步:

.container {
display: flex;
height: 100vh;
}
.left-list, .right-list {
height: 100%;
overflow-y: auto;
flex: 1;
}
优化性能方案
对于大数据列表,可采用虚拟滚动技术(如 vue-virtual-scroller)减少 DOM 节点:
import { RecycleScroller } from 'vue-virtual-scroller';
export default {
components: { RecycleScroller }
}
动态内容联动
若内容高度动态变化,需监听内容变化并重新计算:
export default {
mounted() {
new ResizeObserver(() => {
this.$refs.rightList.scrollTop = this.$refs.leftList.scrollTop;
}).observe(this.$refs.leftList);
}
}
注意事项
- 滚动事件频繁触发,需使用防抖或标志位控制
- 移动端需考虑 touch 事件兼容性
- 同步精度受容器 padding/margin 影响






