vue组件的路由高亮问题

vue组件的路由高亮问题

之前我对于路由的高亮都是使用缓存,给他的所有路由遍历一遍,每点击一下的时候,给他的当前值高亮,赋值active。后来发现一刷新就不行,高亮的就变成默认值0了,这里主要是将这个问题的解决办法。

第一种是通过这样的添加类:

.router{
        font: 12px/40px '微软雅黑';
        background: pink;
        background: pink;
        color: white;
        cursor: pointer;
        text-align: center;
        display: inline-block;
        width: 40px;
        background: pink;
        &.isActive{
            background: blue;
            color:red;
        }
    }

第二种是监听path:

原本的代码是这样的:

<template>
<div id="main">
    <ul style="height:40px;background:pink;">
        <li  class="router" v-for="(item,index) in items" :key="index" style="float:left;" :class="item.isActive?'isActive':''" @click="routerTo(item,index)">
            <span >{{item.name}}</span>
        </li>
    </ul>
    <router-view></router-view>
    </div>
    
</template>
<script>
    export default {
        data () {
            return {
                activeIndex2:'0',
                items:[
                    {name:'twoPage',code:'twoPage',path:'/twoPage',defaultIcon:require('@/assets/icon/BehaviorRank-default.png'),
                    activeIcon:require('@/assets/icon/behaviorrank-active.png'),isActive:true},
                    {name:'three',code:'three',path: '/three',defaultIcon:require('@/assets/icon/ChannelAllocation-default.png'),
                    activeIcon:require('@/assets/icon/ChannelAllocation-active.png'),isActive:false},
                    {name:'four',code:'four',path:'/four',defaultIcon:require('@/assets/icon/myReport-default.png'),
                    activeIcon:require('@/assets/icon/myReport-active.png'),isActive:false},
                ],
            }
        },
        methods:{
            routerTo(item,index) {
                 for (let i = 0; i < this.items.length; i++) {
                    this.items[i].isActive=false
                    
                }
                this.items[index].isActive=true
                this.$router.push({name:item.name})
               
            },
        }
    }
</script>
<style lang='less'>
#main{
    .router{
        font: 12px/40px '微软雅黑';
        background: pink;
        background: pink;
        color: white;
        cursor: pointer;
        text-align: center;
        display: inline-block;
        width: 40px;
        background: pink;
        
    }
    .isActive{
            background: blue;
            color:red;
        }
    
}

</style>

效果:
在这里插入图片描述
但如果点击刷新会这样:高亮的Index跑到了初始化0的位置。
在这里插入图片描述
如何解决这种问题,
有一种方法是通过缓存sessionStorage。每次点击一下就存入缓存,刷新就从变量取值,变量没有值就从缓存取值。但一直存一直取可能有的人觉得麻烦。
还有一种方法就是初始化的时候获取路由,根据不同的路由激活对应的导航

created(){
            // var path=window.location.hash.slice(2);//没有参数时这种写法也可以,不推荐
            var path=this.$route.name//推荐这种
            console.log(path)
            if(path){
                for (let i = 0; i < this.items.length; i++) {
                    this.items[i].isActive=false
                }
                switch(path){
                    case 'twoPage':
                    this.items[0].isActive=true;
                    break;
    
                    case 'three':
                    this.items[1].isActive=true;
                    break;
    
                    case 'four':
                    this.items[2].isActive=true;
                    break;
                }
            }
        },

第三种 使用elementui的sub-menu 的 default-active属性

menu:
主要是 :default-active="$route.path"通过路由监听,然后根据不同路由实现默认的高亮

<template>
    <div class="menu">
      <el-menu  :default-active="$route.path"  class="el-menu-demo" background-color="#0f2c70"
      text-color="#fff" active-text-color="#ffd04b" mode="horizontal" >
      <sub-menu v-for="(item,index) in menuList" :key="item.id" :menuItem="item"></sub-menu>
      </el-menu>
    </div>
</template>
<script>
import subMenu from './ElMenu.vue'
export default {
  components:{
    subMenu
  },
  data() {
    return {
      menuList: [],
    };
  },
  methods:{
    async getList(){
      let res = await queryPtMenuTreeList()
      this.menuList = res.data
    }
  },
  created(){
    this.getList()
  }
};
</script>
<style lang="less">
  .menu{
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #0f2c70;
  }
</style>

elMenu
el-submenuel-menu-item需要注意的是 ,index必须是 当前item的path属性,否则default-active="$route.path无法实现效果

<template>
    <el-submenu :index="menuItem.path" v-if="menuItem.children && menuItem.children.length > 0" 
        :popper-append-to-body="false">
        <template #title>{{menuItem.name}}</template>
        <sub-menu v-for="(it,index) in menuItem.children" :key="it.id" :menuItem="it"></sub-menu>
    </el-submenu>
    <el-menu-item :index="menuItem.path" v-else @click="routerTo(menuItem)">{{menuItem.name}}</el-menu-item>
</template>
<script>
import subMenu from '@/components/ElMenu.vue'
export default {
  name: "sub-menu",
  components:{
      subMenu
  },
  data() {
    return {
        activeIndex:'/home'
    };
  },
  props:{
      menuItem:''
  },
  methods:{
    routerTo(menuItem){
        this.$router.push({path:menuItem.url})
    }
  }
};
</script>
<style lang="less">
</style>



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue 3 中,可以使用 Vue Router 进行路由跳转和导航高亮。下面是一个简单的示例: 1. 首先,确保已经安装了 Vue Router。你可以使用以下命令进行安装: ``` npm install vue-router@next ``` 2. 在你的应用程序的入口文件(通常是 `main.js` 或 `main.ts`)中,导入 Vue Router 并创建一个实例: ```javascript import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import App from './App.vue' const router = createRouter({ history: createWebHistory(), routes: [ // 定义你的路由 // { path: '/home', component: Home } ] }) const app = createApp(App) app.use(router) app.mount('#app') ``` 3. 在你的模板中,使用 `<router-link>` 组件来生成导航链接。该组件会自动根据当前路由状态添加一个 `router-link-active` 类,你可以使用该类来设置导航高亮样式。 ```html <router-link to="/home">Home</router-link> <router-link to="/about">About</router-link> ``` 4. 如果你需要在导航链接被点击时进行一些操作,可以使用路由守卫。例如,你可以在导航链接被激活时添加一个自定义类: ```javascript router.beforeEach((to, from, next) => { // 在每次导航前执行操作 const activeLink = document.querySelector('.router-link-active') if (activeLink) { activeLink.classList.remove('router-link-active') } next() }) ``` 这样,当用户点击导航链接时,当前链接会自动添加 `router-link-active` 类,并在下次导航前移除。 请注意,以上只是一个简单的示例,你需要根据你的具体需求进行调整。如果你想了解更多关于 Vue Router 的用法和配置,请查阅官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值