代码参考:https://www.cnblogs.com/ShiQi-XiaoXiao/p/17665260.html
实现vue3项目中目录横向滚动组件及左右按钮切换滚动
准备工作:
let groupList = ref([{name:123},......])//展示数组
const scrollGroupList = ref(null);//dom元素ref绑定
let btnLeft = ref(0) //0-不展示 1-显示 2 -禁用
let btnRight = ref(0)
首先,是按钮部分:按钮要根据中间内容是否超出限定区域来展示的,其次,也要根据中间内容部分来进行按钮的禁选状态
1:左右点击控制元素的滚动
const scrollBtn = (dir) => {
if (scrollGroupList.value) {
dir == 'right' ? scrollGroupList.value.scrollBy({
left: 600, // 每次点击滚动的距离
behavior: 'smooth',
}) : scrollGroupList.value.scrollBy({
left: -600, // 每次点击滚动的距离
behavior: 'smooth',
});
}
updateButtonStates()
}
2: 控制按钮的显示/隐藏/禁用
const updateButtonStates = () => {
if (scrollGroupList.value) {
let scrollLeft = scrollGroupList.value.scrollLeft;
let scrollWidth = scrollGroupList.value.scrollWidth;
let clientWidth = scrollGroupList.value.clientWidth;
btnLeft.value = scrollLeft === 0 ? 2 : 1; //为0时禁用按钮
btnRight.value = scrollLeft + clientWidth >= scrollWidth ? 2 : 1; //超出范围后禁用按钮
}
};
3:组件初始化时的按钮展示状态
const isShowBtn = () => {
if (scrollGroupList.value) {
const outerWidth = scrollGroupList.value.offsetWidth;
const clinetWidth = scrollGroupList.value.querySelector('.groupListCount').offsetWidth;
if (clinetWidth > outerWidth) {
btnLeft.value = 2
btnRight.value = 1
}
}
}
ok,接下来进行函数拼接,首先是组件加载时判断按钮是否展示,其次像滚动区域挂载上滚动事件
onMounted(() => {
isShowBtn()
scrollGroupList.value.addEventListener('scroll', updateButtonStates);
})
之后是组件销毁
onBeforeUnmount(() => {
scrollGroupList.value.removeEventListener('scroll', updateButtonStates);
})