1、组件
<template>
<div class="switch-tab">
<div class="switch-tab-left" @click="leftClick">
<el-icon :size="24" color="rgba(99, 149, 255, 1)"><ArrowLeft /></el-icon>
</div>
<!-- 显示的区域 -->
<div class="switch-tab-wrap">
<!-- 滑动的区域 -->
<div class="switch-tab-scroll-content" :class="id">
<slot />
</div>
</div>
<div class="switch-tab-right" @click="rightClick">
<el-icon :size="24" color="rgba(99, 149, 255, 1)"><ArrowRight /></el-icon>
</div>
</div>
</template>
<script setup>
import { reactive, ref } from "vue";
/*******************************定义属性props***************************************/
const props = defineProps({
moveWidth: {
// 左右移动基础值
type: Number,
default: 100,
},
id: { // 唯一性
type: String,
default: `switch-scroll`,
},
});
/*******************************定义变量***************************************** */
/******************************定义函数*******************************************/
const leftClick = () => {
let dom = document.querySelector(`.${props.id}`);
if (dom.offsetLeft >= -props.moveWidth) {
dom.style.left = `0px`;
} else {
dom.style.left = `${dom.offsetLeft + props.moveWidth}px`;
}
};
const rightClick = () => {
let dom = document.querySelector(`.${props.id}`);
let domWrap = document.querySelector(".switch-tab-wrap");
if (
dom.scrollWidth + dom.offsetLeft - props.moveWidth <=
domWrap.offsetWidth
) {
dom.style.left = `${domWrap.offsetWidth - dom.scrollWidth}px`;
} else {
dom.style.left = `${dom.offsetLeft - props.moveWidth}px`;
}
};
</script>
<style lang='scss' scoped>
.switch-tab {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 100%;
&-left,
&-right {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 82px;
background: rgba(52, 118, 255, 0.04);
border-radius: 2px;
cursor: pointer;
}
&-wrap {
position: relative;
display: flex;
justify-content: flex-start;
align-items: center;
width: calc(100% - 100px);
height: 100%;
padding: 0 10px;
overflow: hidden;
transition: all 0.3s;
}
&-scroll-content {
position: absolute;
left: 0px;
display: flex;
align-items: center;
width: auto;
height: 36px;
transition: all 0.3s;
}
}
</style>
View Code
2、父组件调用
<template>
<zy-switch-tab :moveWidth="187" id="to-do">
<div class="switch-tab-scroll-item" v-for="item in 30" :key="item">
{{ item }}
</div>
</zy-switch-tab>
</template>
<script setup>
import { reactive } from "vue";
/*******************************定义属性props***************************************/
/*******************************定义变量***************************************** */
/******************************定义函数*******************************************/
</script>
<style lang='scss' scoped>
.switch-tab-scroll-item {
width: 100px;
font-size: 15px;
font-weight: 400;
color: #000;
}
</style>