vuejs切换导航条高亮路由高亮做法

我的GitHub前端经验总结,喜欢的话请点star✨✨Thanks.:https://github.com/liangfengbo/frontend-develop

vuejs导航条高亮我的做法:

  • 用一个数组存导航条,用v-for循环它,这样可以减少代码,二可以使用它的下标来判断高亮,三还可以获取后端的导航信息来遍历
  • 重点是在:routerLink(index, path)函数,传入当前点击的下标,自定义一个下标,判断是否相等就用三元符号判断多给一个高亮样式
  • 如何解决刷新就不高亮或第一个高亮了,很简单,监听一下当前路由在判断就好了
  • 具体代码都在下面了

效果图:

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数据

// 导航条
data() {
  return {
    nav: [
      {title: '首页', en: 'Code', path: '/'},
      {title: '开源', en: 'Source', path: '/source'},
      {title: '关于', en: 'About', path: '/about'},
    ],
    navIndex: 0,
  }
},

methods方法:

/**
 * 路由跳转
 * @param index
 * @param link
*/
routerLink(index, path) {
  // 点击哪个路由就赋值给自定义的下下标
  this.navIndex = index;
  // 路由跳转
  this.$router.push(path)
},

/**
 * 检索当前路径
 * @param path
*/
checkRouterLocal(path) {
  // 查找当前路由下标高亮
  this.navIndex = this.nav.findIndex(item => item.path === path);
}

监听路由变化获取当前路由

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;
}

/*导航普通状态*/
.item-cn {
  color: #1c2438;
  font-weight: 800;
}

/*导航普通状态*/
.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;
}
posted @ 2018-05-29 10:02  梁凤波  阅读(452)  评论(0编辑  收藏  举报