<template>
<view class="nav-bar">
<scroll-view scroll-x="true" class="scroll-view" show-scrollbar="false">
<view class="nav-item" v-for="(item, index) in navItems" :key="index" @tap="selectItem(index)">
<text :class="['nav-text', { active: currentIndex === index }]"
:style="{ fontSize: fontSize + 'rpx' }">{{ item }}</text>
<view :class="['indicator', { active: currentIndex === index }]" :style="{
width: currentIndex === index ? indicatorWidth + 'rpx' : '0',height: dynamicHeight + 'rpx'}"></view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
name: 'NavBar',
props: {
dynamicHeight: { //active下滑高度
type: [Number, String],
default: 6
},
indicatorWidth: { //active下滑宽度
type: [Number, String],
default: 40
},
fontSize: { //字体大小
type: [Number, String],
default: '28'
},
navItems: {
type: Array,
default: () => ['首页',]
},
defaultIndex: {
type: Number,
default: 0
}
},
data() {
return {
currentIndex: this.defaultIndex
}
},
methods: {
selectItem(index) {
this.currentIndex = index
this.$emit('item-selected', index)
}
}
}
</script>
<style scoped>
.nav-bar {
background-color: #ffffff;
padding: 10rpx 0;
border-bottom: 1rpx solid #f0f0f0;
}
.scroll-view {
white-space: nowrap;
}
.nav-item {
display: inline-block;
padding: 0 20rpx;
position: relative;
text-align: center;
}
.nav-text {
color: #333333;
font-weight: bold;
line-height: 60rpx;
}
.active {
color: #27ae60;
font-weight: bold;
}
.indicator {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 0;
background-color: #27ae60;
transition: width 0.3s;
}
</style>
使用组件
<template>
<view>
<NavBar :navItems="myNavItems" :fontSize="26" :dynamicHeight="4" :indicatorWidth="30" @item-selected="onItemSelected" />
<!-- 其他页面内容 -->
</view>
</template>
<script>
import NavBar from './xztdemoNavBar.vue'
export default {
components: {
NavBar
},
data() {
return {
myNavItems: ['首页', '北京同仁堂', '正官庄', '仙芝楼', '江中', 'swisses', '品牌馆'],
// myNavItems: ['首页', '分类', '购物车', '我的']
}
},
methods: {
onItemSelected(index) {
console.log('Selected item index:', index)
// 处理选中项的逻辑
}
}
}
</script>