美文网首页
导航栏活跃状态

导航栏活跃状态

作者: autumn_3d55 | 来源:发表于2022-01-19 16:33 被阅读0次

1. 图示

image.png

根据路由元信息和导航栏数据进行判断,相等即为活跃高亮,不相等则不高亮。

2.实现方法

  • 首先在router.js 文件下 ,给各个路由添加路由元信息
  • 通过 this.$route.meta.active; 获取路由元信息,然后和数组的唯一标识进行判断,如果为true则高亮,否则不高亮。
    <span v-show="active == i.id"></span>
  • 在通过 watch 监听器实时监听路由的变化
//公告中心详情页面
      {
        path: '/noticeDetail',
        name: 'NoticeDetail',
        component: resolve => require(['@/views/index/NoticeDetail'], resolve),
        meta: {
          active: '2'
        }
      },
      //帮助中心页面
      {
        path: '/help',
        name: 'Help',
        component: resolve => require(['@/views/index/Help'], resolve),
        meta: {
          active: '3'
        }
      },
  • 我封装了一个navTab 组件
<!--顶部导航封装-->
<template>
  <div class="NavTop">
    <div class="box">
      <ul class="list">
        <li
          class="list_item"
          v-for="(i, index) in navList"
          :key="i.id"
          @click="toDetail(i.path)"
        >
          {{ i.key }}
          <span v-show="active == i.id"></span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  naem: "NavTop",
  props: {
    navList: {
      type: Array,
      default: {},
    },
  },
  data() {
    return {
      active: "1",
    };
  },
  methods: {
    toDetail(path) {
      this.$router.push(path);
    },
  },
  watch: {
    $route() {
      if (this.$route.meta.active) {
        this.active = this.$route.meta.active;
      } else {
        this.active = ''
      }
    },
  },
  created() {
    if (this.$route.meta.active) {
      this.active = this.$route.meta.active;
    }
  },
};
</script>
  • 这个传过去的数组 navList

```navList: [
        {
          id: 1,
          key: '首页',
          path: '/index/home'
        },
        {
          id: 2,
          key: '公告中心',
           path: '/index/noticeCenter'
        },
        {
          id: 3,
          key: '帮助中心',
          path: '/index/help'
        },
        
      ]
    }

- 最后,即可实现导航栏活跃高亮。·

相关文章

网友评论

      本文标题:导航栏活跃状态

      本文链接:https://www.haomeiwen.com/subject/fjzkhrtx.html