<template> <view class="tabs"> <view class="tabs-header both"> <view v-for="(tab, index) in tabs" :key="index" :class="{ 'active': activeTab === index }" @click="changeTab(index)"> {{ tab }} </view> </view> <view class="tabs-content"> <slot :name="tabs[activeTab]"></slot> </view> </view> </template> <script setup> import { ref } from 'vue' const props = defineProps({ tabs: { type: Array, required: true }, }) let activeTab = ref(0) const changeTab = (index) => { activeTab.value = index } </script> <style lang="scss" scoped> .tabs { display: flex; flex-direction: column; height: 100%; .tabs-header { display: flex; justify-content: space-between; align-items: center; height: 50px; font-size: 30rpx; } .tabs-content { flex: 1; overflow-y: auto; } } .active { position: relative; color: #8a74ee; } .active::after { content: ""; position: absolute; width: 40rpx; height: 8rpx; background-color: #8a74ee; left: 0rpx; right: 0rpx; bottom: -50%; margin: auto; border-radius: 16rpx; } </style>帮我把这个组件优化成选项卡下面插槽中内容左右滑动时上面标签也会随之滑动
时间: 2024-02-15 08:27:14 浏览: 91
ditchnet-tabs-taglib_0.8.zip_Tabú_ditchnet ta_ditchnet-tabs-tagl
好的,可以尝试使用 better-scroll 库来实现选项卡下面内容左右滑动时上面标签也会随之滑动的效果,以下是代码实现:
<template>
<div class="tabs">
<div class="tabs-header both">
<div v-for="(tab, index) in tabs" :key="index" :class="{ 'active': activeTab === index }" @click="changeTab(index)">
{{ tab }}
</div>
</div>
<div class="tabs-content" ref="wrapper">
<div class="tabs-inner">
<slot :name="tabs[activeTab]"></slot>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import BScroll from 'better-scroll'
const props = defineProps({
tabs: {
type: Array,
required: true
}
})
let activeTab = ref(0)
let tabsScroll = null
const changeTab = (index) => {
activeTab.value = index
tabsScroll.scrollToElement(`.tabs-header > div:nth-child(${index + 1})`, 300, true, true)
}
onMounted(() => {
tabsScroll = new BScroll($refs.wrapper, {
scrollX: true,
scrollY: false,
eventPassthrough: 'vertical'
})
})
</script>
<style lang="scss" scoped>
.tabs {
display: flex;
flex-direction: column;
height: 100%;
.tabs-header {
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
font-size: 30rpx;
> div {
position: relative;
padding: 0 30rpx;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
transition: opacity 0.2s ease-in-out;
}
&.active::before {
opacity: 1;
background-color: #8a74ee;
border-radius: 16rpx;
}
}
}
.tabs-content {
flex: 1;
overflow: hidden;
.tabs-inner {
display: flex;
transition: transform 0.2s ease-in-out;
> * {
flex-shrink: 0;
width: 100%;
height: 100%;
}
}
}
}
</style>
主要变化如下:
1. 引入 better-scroll 库,使用 onMounted 钩子在组件挂载后初始化滚动实例。
2. 在 HTML 部分,将插槽内容包裹在一个 .tabs-inner 容器中,用于实现左右滑动效果。
3. 在 CSS 部分,对 .tabs-header 中的选项卡标签进行样式调整,使用 ::before 伪类实现选中状态下的底部标识。
经过以上优化,现在选项卡下面插槽中内容左右滑动时上面标签也会随之滑动了,希望能对你有所帮助。
阅读全文