vue实现底部导航
Vue 实现底部导航的方法
使用 Vue Router 和自定义组件
创建一个名为 BottomNavigation.vue 的组件,用于渲染底部导航栏。在模板中使用 <router-link> 实现路由跳转。
<template>
<div class="bottom-navigation">
<router-link
v-for="item in navItems"
:key="item.path"
:to="item.path"
class="nav-item"
>
<span>{{ item.label }}</span>
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
navItems: [
{ path: '/home', label: '首页' },
{ path: '/discover', label: '发现' },
{ path: '/cart', label: '购物车' },
{ path: '/profile', label: '我的' }
]
}
}
}
</script>
<style scoped>
.bottom-navigation {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
background: #fff;
padding: 8px 0;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}
.nav-item {
display: flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: #666;
}
.router-link-exact-active {
color: #42b983;
}
</style>
在 App.vue 中引入组件
确保底部导航栏固定在页面底部,并设置主内容区域的样式避免遮挡。
<template>
<div id="app">
<router-view/>
<BottomNavigation/>
</div>
</template>
<script>
import BottomNavigation from './components/BottomNavigation.vue'
export default {
components: { BottomNavigation }
}
</script>
<style>
#app {
padding-bottom: 60px; /* 等于导航栏高度 */
}
</style>
配置 Vue Router
在路由配置文件中设置与导航栏对应的路由。
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Discover from './views/Discover.vue'
import Cart from './views/Cart.vue'
import Profile from './views/Profile.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/home', component: Home },
{ path: '/discover', component: Discover },
{ path: '/cart', component: Cart },
{ path: '/profile', component: Profile },
{ path: '/', redirect: '/home' }
]
})
添加图标支持
安装图标库如 vue-awesome 或使用字体图标,增强导航栏视觉效果。
npm install vue-awesome
在组件中引入图标:
<template>
<router-link :to="item.path" class="nav-item">
<v-icon :name="item.icon"/>
<span>{{ item.label }}</span>
</router-link>
</template>
<script>
import 'vue-awesome/icons/home'
import 'vue-awesome/icons/compass'
import 'vue-awesome/icons/shopping-cart'
import 'vue-awesome/icons/user'
export default {
data() {
return {
navItems: [
{ path: '/home', label: '首页', icon: 'home' },
{ path: '/discover', label: '发现', icon: 'compass' },
{ path: '/cart', label: '购物车', icon: 'shopping-cart' },
{ path: '/profile', label: '我的', icon: 'user' }
]
}
}
}
</script>
响应式设计
通过媒体查询调整导航栏在不同设备上的显示效果。

@media (min-width: 768px) {
.bottom-navigation {
max-width: 500px;
margin: 0 auto;
border-radius: 20px 20px 0 0;
}
}






