vue实现顶部导航栏以及跳转
作者:LZ可是懒大王
这篇文章主要介绍了vue实现顶部导航栏以及跳转方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
一、项目结构

二、实现
1、参考Element
我们可以快速的编写一个简单的顶部导航栏

2、我们在Element的基础上
将我们的参数添加到代码中,需要注意的是,如果在父层级的index中,如果没有添加 “/”标识的话,router的自动跳转会出问题,在父层级跳到其他父层级的自层级下后,再次返回该层级,路径会直接修改后缀,从而导致跳转失败
<template>
<div>
<el-header>
<div>
<el-row style="text-align: center;min-height: 60px;">
<el-col :span="4">
<el-image
class="brandArea"
:src="brandImg"
:fit="fit"></el-image>
</el-col>
<el-col :span="18">
<el-menu
router="router"
:default-active="activeIndex"
:active-text-color="activeColor"
class="el-menu-demo"
style="position:static;"
mode="horizontal"
@select="handleSelect">
<el-row>
<el-col :span="4">
<el-menu-item index="/home">首页</el-menu-item>
</el-col>
<el-col :span="4">
<el-submenu index="/blog">
<template slot="title">博客</template>
<el-menu-item index="/blog/blogMain">首页</el-menu-item>
<el-menu-item index="/blog/blogSelf">我的</el-menu-item>
</el-submenu>
</el-col>
<el-col :span="4">
<el-menu-item index="2">音乐</el-menu-item>
</el-col>
<el-col :span="4">
<el-menu-item index="3" disabled>视频</el-menu-item>
</el-col>
<el-col :span="4">
<el-menu-item index="4">游戏</el-menu-item>
</el-col>
<el-col :span="4">
<el-menu-item index="5">社区</el-menu-item>
</el-col>
</el-row>
</el-menu>
</el-col>
<el-col :span="2">
<el-image
class="headArea"
:src="headImg"
:fit="fit"></el-image>
</el-col>
</el-row>
</div>
</el-header>
</div>
</template><script>
import {
queryToken,
} from "@/api/base/base.js"
import "@/css/base.css"
export default {
name: "homeHead",
data(){
return{
fit: 'contain',
headImg: require("@/img/headImg.jpg"),
brandImg: require("@/img/brand_img.jpg"),
activeIndex: '/home',
activeColor: '#409EFF',
}
},
methods: {
getToken(){
queryToken().then(
response => {
console.info(response);
}).catch(() => {
});
},
handleSelect(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>3、这是导航栏代码
这时我们就需要考虑,我们已经编写了导航栏,如何把导航栏添加到每个页面上了,一是编写公共项目,二是在每个页面上都添加头文件,显然,二我们是不考虑的,所以我们需要编写一个公共文件,或者直接使用App.vue
4、首先考虑直接使用App.vue的情况
我们先将App.vue改进下
<template>
<div>
<div>
<HomeHead></HomeHead>
</div>
<div>
<router-view></router-view>
</div>
</div>
</template><script>
import HomeHead from '@/views/base/homeHead'
export default {
name: 'App',
components: {
HomeHead
}
}
</script>5、但是我们在第一步就会发现问题
登陆页以及注册页也出现了导航栏,我们肯定不希望这种情况出现的,所以我们就需要开始写路由,然后在路由中添加跳转路径,以及显示条件

6、修改路由
先在路由中添加keepAlive字段,然后修改App.vue,加入v-if


7、到这个时候我们已经完成了
一个简单的导航栏的实现,这时我们在写路由的时候是不需要填写子层级的,只需要在路径上添加对应父层级的标识即可
例如:

注:
其中的class文件我并没有添加什么特殊的,大家可以随便设置下,因为比较简单,所以代码就不上传了,等我写完整个项目后我会一步步的写出来我的项目流程的
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
