subsection.vue
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<template>
<div class="u-subsection">
<div class="u-subsection-item" :class="{ active: index + 1 === value }" v-for="(item, index) in list" :key="index" @click="handleClick(index + 1)" ref="tabItems">
{{ item.label }}
</div>
<!-- 滑动高亮条 -->
<div class="slider" :style="sliderStyle"></div>
</div>
</template>
<script>
export default {
name: 'USubsection',
props: {
list: {
type: Array,
default: () => [],
},
value: {
type: Number,
default: 1,
},
},
data() {
return {
sliderStyle: {
left: '0vw',
width: '0vw',
background: '#ffd700', // 初始黄色
},
}
},
mounted() {
// 初始化位置
this.$nextTick(() => {
this.setSliderPosition(this.value - 1)
})
},
watch: {
// 监听选中变化,自动滑动
value: {
handler(newVal) {
this.$nextTick(() => {
this.setSliderPosition(newVal - 1)
})
},
},
},
methods: {
handleClick(val) {
this.$emit('input', val)
},
// 设置滑动条位置和宽度
setSliderPosition(index) {
if (!this.$refs.tabItems || !this.$refs.tabItems[index]) return
const item = this.$refs.tabItems[index]
// 转换成 vw
const vwLeft = (item.offsetLeft / window.innerWidth) * 100
const vwWidth = (item.offsetWidth / window.innerWidth) * 100
this.sliderStyle.left = vwLeft + 'vw'
this.sliderStyle.width = vwWidth + 'vw'
// 左边黄色 右边绿色(只改这里!)
if (index === 0) {
this.sliderStyle.background = '#ffd700' // 左
} else {
this.sliderStyle.background = '#32b92b' // 右
}
},
},
}
</script>
<style scoped>
.u-subsection {
width: 16vw;
height: 3vw;
display: flex;
position: relative;
gap: 2vw;
padding: 0.2vw 0.3vw;
background: #e0e0e0;
border-radius: 0.6vw;
margin: 0vw 0;
overflow: hidden;
border: 0.12vw solid #3f3e3e;
box-shadow: 0.2vw 0.2vw 0.2vw #333, 0.3vw 0.3vw 1vw rgba(0, 0, 0, 0.3);
}
.u-subsection-item {
padding: 0.5vw 1.29vw;
border-radius: 0.4vw;
cursor: pointer;
font-size: 1vw;
color: #333;
position: relative;
z-index: 2;
transition: color 0.2s ease;
}
.u-subsection-item.active {
color: #fff;
}
.slider {
width: 6.6vw;
height: 2.2vw;
position: absolute;
top: 0.3vw;
bottom: 0.6vw;
border-radius: 0.4vw;
transition: left 0.25s linear, width 0.2s ease, background 0.2s linear;
z-index: 1;
}
</style>