vuejs 切換導航條高亮(路由菜單高亮)的方法示例
我的GitHub前端經(jīng)驗總結(jié),喜歡的話請點star:Thanks.: https://github.com/liangfengbo/frontend-develop
vuejs導航條高亮我的做法:
- 用一個數(shù)組存導航條,用v-for循環(huán)它,這樣可以減少代碼,二可以使用它的下標來判斷高亮,三還可以獲取后端的導航信息來遍歷
- 重點是在:routerLink(index, path)函數(shù),傳入當前點擊的下標,自定義一個下標,判斷是否相等就用三元符號判斷多給一個高亮樣式
- 如何解決刷新就不高亮或第一個高亮了,很簡單,監(jiān)聽一下當前路由在判斷就好了
具體代碼都在下面了
效果圖:
html代碼
<div class="nav-box"> <!-- 導航列表 --> <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ù)
// 導航條 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) { // 點擊哪個路由就賦值給自定義的下下標 this.navIndex = index; // 路由跳轉(zhuǎn) this.$router.push(path) }, /** * 檢索當前路徑 * @param path */ checkRouterLocal(path) { // 查找當前路由下標高亮 this.navIndex = this.nav.findIndex(item => item.path === path); }
監(jiān)聽路由變化獲取當前路由
watch: { "$route"() { // 獲取當前路徑 let path = this.$route.path; // 檢索當前路徑 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; } /*導航普通狀態(tài)*/ .item-cn { color: #1c2438; font-weight: 800; } /*導航普通狀態(tài)*/ .item-en { color: #666; font-size: 12px; } /*導航高亮*/ .item-cn-active { color: #2d8cf0; } /*導航高亮*/ .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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue單頁面打包文件大?首次加載慢?nginx帶你飛,從7.5M到1.3M蛻變過程(推薦)
這篇文章主要介紹了vue單頁面打包文件大?首次加載慢?nginx帶你飛,從7.5M到1.3M蛻變過程,需要的朋友可以參考下2018-01-01一文搞懂Vue3中的異步組件defineAsyncComponentAPI的用法
這篇文章主要介紹了一文搞懂Vue3中的異步組件,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07vue3如何實現(xiàn)表格內(nèi)容無縫滾動(又寫了一堆冗余代碼)
這篇文章主要給大家介紹了關(guān)于vue3如何實現(xiàn)表格內(nèi)容無縫滾動的相關(guān)資料,在Vue3項目中難免會遇到讓列表滾動的需求,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04關(guān)于vue-admin-template模板連接后端改造登錄功能
這篇文章主要介紹了關(guān)于vue-admin-template模板連接后端改造登錄功能,登陸方法根據(jù)賬號密碼查出用戶信息,根據(jù)用戶id與name生成token并返回,userinfo則是對token進行獲取,在查出對應值進行返回,感興趣的朋友一起看看吧2022-05-05