navBar组件
<template>
<div class="navBar" ref="navBar">
<div class="navs" ref="navs" :style="{overflow:index!=-1?'hidden':'none'}">
<div class="navItems" :data-index="index" :refs="'navItems' + index" v-for="(item, index) in uls" :key="item.id">
{{ item.text }}
</div>
</div>
<div class="more" ref="more" v-show="index!=-1">
<span @click="show = !show">更多</span>
<div class="dropdown" v-if="show">
<div class="dropItem" v-for="(item) in uls.slice(index-1, uls.length)" :key="item.id">
{{ item.text }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'navBar',
props:{
uls:{
type:Array
}
},
data() {
return {
index: -1,
show: false
}
},
mounted() {
this.updateNav()
},
methods: {
updateNav() {
this.$nextTick(() => {
let barWidth = this.$refs.navBar.offsetWidth
let moreWidth = this.$refs.more.offsetWidth
let doms = Array.from(this.$refs.navs.children)
let width = 0
for (let i = 0; i <= doms.length; i++) {
width += doms[i].offsetWidth
if (width + moreWidth > barWidth) {
this.index = doms[i].dataset.index
break;
}
}
})
}
}
}
</script>
<style lang="scss" scoped>
.navBar{
display: flex;
}
.navs {
line-height: 40px;
display: flex;
box-sizing: border-box;
}
.navItems {
background-color: #fff;
padding: 0 10px;
white-space: nowrap;
color: #000;
margin-right: 10px;
border: 1px solid rgba(0, 0, 0, .06);
cursor: pointer;
}
.navItems:hover {
color: #1890ff;
}
.more {
white-space: nowrap;
position: relative;
flex-shrink: 0;
span{
display: flex;
width: 100%;
height: 100%;
align-items: center;
background-color: #f0f2f5;
padding: 0 10px;
box-sizing: border-box;
}
}
.dropdown{
position: absolute;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
left: -50%;
top:calc(100% + 10px);
background-color: #fff;
box-shadow: 0 0 10px #999;
border-radius: 5px;
width: 150px;
max-height: 250px;
padding: 10px 0;
overflow-y: scroll;
}
.dropItem{
width: 100%;
line-height: 2;
padding-left: 5px;
}
.dropItem:hover{
background-color: #dbd9d9;
}
</style>
使用
<template>
<div>
<div class="header">
<navBar :uls="uls"></navBar>
</div>
</div>
</template>
<script>
import navBar from "@/components/navBar.vue";
export default {
name:'HomeView',
components:{
navBar
},
data(){
return {
uls: [
{
text: '标题1'
},
{
text: '标题2'
},
{
text: '标题3'
},
{
text: '标题4'
},
{
text: '标题5'
},
{
text: '标题6'
},
{
text: '标题7'
},
{
text: '标题5'
},
{
text: '标题6'
},
{
text: '标题7'
},
],
}
}
}
</script>
效果