摘要
本文讲述个人亲自实践的在vue中,选择不同的导航栏后,高亮选中的栏目的实现方法。
本文讲述个人亲自实践的在vue中,选择不同的导航栏后,高亮选中的栏目的实现方法。
Vue中导航栏想必大家经常使用,由于导航栏为整个网站的公共部分,因此很多朋友会把vue中的导航栏提取为公共的模板,此时在选择不同的导航栏按钮后,如何让选中的高亮成了一个问题,本文就将讲述如何解决并实现上述问题。
重点在于,本文并未像网上其他资料上通过各种函数来控制,本文实现遵循vue的官方实现来解决,无需增加其他任何多余的代码。
本文vue结构如下:
其中,Home.vue为一个页面,nav_top.vue为导航栏的模板组件,其代码如下:
Home.vue
<template> <div class="home"> <navbartop :nav_tab="currentNav"></navbartop> </div> </template> <script> import navbartop from '../../components/nav_foot/nav_top' export default { components:{ navbartop }, data() { return { currentNav: '2' }; }, methods: { handleSelect(key, keyPath) { console.log(key, keyPath); } } } </script>
nav_top.vue内容为:
<template> <div class="nav_top"> <el-menu router :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b"> <el-menu-item index="1">首页</el-menu-item> <el-menu-item index="2">车找人信息</el-menu-item> <el-menu-item index="3">人找车信息</el-menu-item> <el-submenu index="4"> <template slot="title">更多内容</template> <el-menu-item index="4-1">拼车故事</el-menu-item> <el-menu-item index="4-2">拼车指南</el-menu-item> <el-menu-item index="4-3">使用指导</el-menu-item> </el-submenu> <el-menu-item index="6" >{{nav_tab}}</el-menu-item> </el-menu> </div> </template> <script> export default { props: { nav_tab: { type: String, required: true } }, data() { return { activeIndex: this.nav_tab // 重新定义数据 } }, computed: { switchStatus: function () { return this.nav_tab // 直接监听props里的status状态 } } } </script>
通过上述代码即可实现,现在讲解下如何实现的选中导航栏后高亮
首先Home.vue中引入nav_top.vue页面,并传入当前应该高亮的导航栏(参数,此处传入的参数和nav_top.vue中index="..."的参数格式必须保持一致)
<navbartop :nav_tab="currentNav"></navbartop>
此时,Home.vue向nav_top.vue传入了一个KEY为nav_tab,value为2的参数
2.1 el-menu-item组件中 index的值必须包含Home.vue中传入的值(只有包含了才会高亮),示例如下
<el-menu-item index="1">首页</el-menu-item>
2.2 nav_top_.vue中的script必须按照以下写法复制
至于为何那样写,注释中已经很明确
通过以上方式,当不同的父页面传入不同的值,即可实现导航栏随之高亮显示。
另外请注意,如果想要实现点击导航栏跳转,一定要在标签里面加上router属性,例如:
<el-menu router >