vuejs 切換導(dǎo)航條高亮(路由菜單高亮)的方法示例
更新時間:2018年05月29日 13:42:39 作者:Liang Fengbo
這篇文章主要介紹了vuejs 切換導(dǎo)航條高亮路由高亮的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
我的GitHub前端經(jīng)驗總結(jié),喜歡的話請點star:Thanks.: https://github.com/liangfengbo/frontend-develop
vuejs導(dǎo)航條高亮我的做法:
- 用一個數(shù)組存導(dǎo)航條,用v-for循環(huán)它,這樣可以減少代碼,二可以使用它的下標(biāo)來判斷高亮,三還可以獲取后端的導(dǎo)航信息來遍歷
- 重點是在:routerLink(index, path)函數(shù),傳入當(dāng)前點擊的下標(biāo),自定義一個下標(biāo),判斷是否相等就用三元符號判斷多給一個高亮樣式
- 如何解決刷新就不高亮或第一個高亮了,很簡單,監(jiān)聽一下當(dāng)前路由在判斷就好了
具體代碼都在下面了
效果圖:

html代碼
<div class="nav-box">
<!-- 導(dǎo)航列表 -->
<li class="nav-item"
v-for="(item, index) in nav"
@click="routerLink(index, item.path)"
:key="index">
<!-- 判斷高亮表 -->
<p :class=" navIndex === index ? 'item-cn item-cn-active' : 'item-cn'">
{{ item.title }}
</p>
<!-- 判斷高亮表 -->
<p :class="navIndex === index ? 'item-en item-en-active' : 'item-en'">
{{ item.en }}
</p>
</li>
</div>
data數(shù)據(jù)
// 導(dǎo)航條
data() {
return {
nav: [
{title: '首頁', en: 'Code', path: '/'},
{title: '開源', en: 'Source', path: '/source'},
{title: '關(guān)于', en: 'About', path: '/about'},
],
navIndex: 0,
}
},
methods方法:
/**
* 路由跳轉(zhuǎn)
* @param index
* @param link
*/
routerLink(index, path) {
// 點擊哪個路由就賦值給自定義的下下標(biāo)
this.navIndex = index;
// 路由跳轉(zhuǎn)
this.$router.push(path)
},
/**
* 檢索當(dāng)前路徑
* @param path
*/
checkRouterLocal(path) {
// 查找當(dāng)前路由下標(biāo)高亮
this.navIndex = this.nav.findIndex(item => item.path === path);
}
監(jiān)聽路由變化獲取當(dāng)前路由
watch: {
"$route"() {
// 獲取當(dāng)前路徑
let path = this.$route.path;
// 檢索當(dāng)前路徑
this.checkRouterLocal(path);
}
},
css樣式
.nav-box {
display: flex;
}
.nav-item {
text-align: center;
padding: 0 32px;
position: relative;
display: inline-block;
font-size: 14px;
line-height: 25px;
}
/*導(dǎo)航普通狀態(tài)*/
.item-cn {
color: #1c2438;
font-weight: 800;
}
/*導(dǎo)航普通狀態(tài)*/
.item-en {
color: #666;
font-size: 12px;
}
/*導(dǎo)航高亮*/
.item-cn-active {
color: #2d8cf0;
}
/*導(dǎo)航高亮*/
.item-en-active {
color: #5cadff;
}
.nav-item:hover .item-cn {
color: #2d8cf0;
}
.nav-item:hover .item-en {
color: #5cadff;
}
.nav-item:after {
position: absolute;
right: 0;
top: 20px;
content: '';
width: 1px;
height: 16px;
background-color: #f8f8f8;
}
.nav-item:after:last-child {
width: 0;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在vue3中使用el-tree-select實現(xiàn)樹形下拉選擇器效果
el-tree-select是一個含有下拉菜單的樹形選擇器,結(jié)合了?el-tree?和?el-select?兩個組件的功能,這篇文章主要介紹了在vue3中使用el-tree-select做一個樹形下拉選擇器,需要的朋友可以參考下2024-03-03
如何解決elementUI打包上線后icon圖標(biāo)偶爾亂碼問題
文章描述了在使用若依框架開發(fā)過程中遇到的圖標(biāo)亂碼問題,通過分析發(fā)現(xiàn)是由于sass編譯器將Unicode編碼轉(zhuǎn)換為明文導(dǎo)致的,文章提供了四種處理方法:使用css-unicode-loader、升高sass版本、替換element-ui的樣式文件和更換打包壓縮方式2025-01-01
Vue如何動態(tài)修改el-table的某列數(shù)據(jù)
這篇文章主要介紹了Vue如何動態(tài)修改el-table的某列數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

