Vue 实现一个头部导航栏
2018-11-04 本文已影响469人
QYiZHong
一个移动端的前端肯定是需要头部导航栏的,头部导航栏需要通过路由知道是否要显示返回按钮,并且根据底部导航栏改变title,还需要判断是否需要隐藏底部导航栏。
演示
![](https://img.haomeiwen.com/i8216167/9fcde459338bfa33.gif)
实现
实现头部导航栏
我们需要在watch里观测是否在二级页面,那么只要知道哪些是一级页面即可。通过topPage配置一级页面的name,每次路由获取to.name就可以进行判断了。只要是二级页面就显示左侧返回按钮并且回调告诉App.vue需要隐藏底部的TabBar。
<template>
<nav id="navigation" class="row">
<div class="col-xs-2" @click="navigationBack">
<i class="iconfont icon-fanhui" v-if="isCanBack"></i>
</div>
<div class="col-xs-8">
<span>{{title}}</span>
</div>
</nav>
</template>
<script>
export default {
name: "navigation",
props: {
title: String
},
data: function () {
return {
isCanBack: false,
}
},
watch: {
$route(to, from) {
let topPage = ['HomeIndex', 'StoreList', 'Me'];
let toName = to.name;
let isNeedShow = true;
for (let i=0;i<topPage.length;i++) {
if (toName === topPage[i]) {
isNeedShow = false;
break;
}
}
this.isCanBack = isNeedShow;
this.$emit('need-hidden-tab-bar', isNeedShow);
}
},
methods: {
navigationBack: function () {
this.$router.go(-1);
}
}
}
</script>
<style scoped>
nav {
background-color: white;
width: 100%;
height: 44px;
border: solid rgb(210, 210, 210);
border-width: 0 0 1px 0;
position: fixed;
margin: auto;
top: 0;
}
div {
text-align: center;
line-height: 44px;
}
span {
font-size: 18px;
font-weight: bold;
}
</style>
# App.vue
<TabBar @select-item="onClickTabBarItem" v-if="isTop"/>
data: function () {
return {
navTitle: '首页',
isTop: true
}
}
methods: {
onClickTabBarItem: function (tag) {
if (tag === 0) {
this.$router.replace({name: "Home"});
this.navTitle = '首页';
} else if (tag === 1) {
this.$router.replace({name: "StoreList"});
this.navTitle = '商户';
} else if (tag === 2) {
this.$router.replace({name: "Me"});
this.navTitle = '我';
}
},
isNeedHiddenTabBar: function (isNeed) {
this.isTop = !isNeed;
}
}
移动到二级页面
首先是在router.js里注册children
import HomeIndex from 'components/home/Index'
import HomeMovie from 'components/home/Movie'
name: 'Home',
path: '/home',
component: Home,
children: [
{
name: 'HomeIndex',
path: 'index',
component: HomeIndex
},
{
name: 'HomeMovie',
path: 'movie',
component: HomeMovie
},
{
path: '',
component: HomeIndex
}
]
在home组件里直接push到HomeIndex
# Home.vue
<template>
<div id="home">
<router-view/>
</div>
</template>
<script>
export default {
name: "home",
created: function () {
this.$router.push({name: 'HomeIndex'});
}
}
</script>
<style scoped>
</style>
#Index.vue
<template>
<div id="index">
<button @click="nextPage">点我进入下一页</button>
</div>
</template>
<script>
export default {
name: "index",
methods: {
nextPage: function () {
this.$router.push({name: 'HomeMovie'})
}
}
}
</script>
<style scoped>
</style>