溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vuejs 切換導(dǎo)航條高亮(路由菜單高亮)的方法示例

發(fā)布時間:2020-09-29 03:49:52 來源:腳本之家 閱讀:222 作者:Liang Fengbo 欄目:web開發(fā)

我的GitHub前端經(jīng)驗總結(jié),喜歡的話請點star:Thanks.: https://github.com/liangfengbo/frontend-develop

vuejs導(dǎo)航條高亮我的做法:

  1. 用一個數(shù)組存導(dǎo)航條,用v-for循環(huán)它,這樣可以減少代碼,二可以使用它的下標(biāo)來判斷高亮,三還可以獲取后端的導(dǎo)航信息來遍歷
  2. 重點是在:routerLink(index, path)函數(shù),傳入當(dāng)前點擊的下標(biāo),自定義一個下標(biāo),判斷是否相等就用三元符號判斷多給一個高亮樣式
  3. 如何解決刷新就不高亮或第一個高亮了,很簡單,監(jiān)聽一下當(dāng)前路由在判斷就好了

具體代碼都在下面了

效果圖:

vuejs 切換導(dǎo)航條高亮(路由菜單高亮)的方法示例

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í)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI