标题所指的情况有很多种,我找过的很多答案要么是没有给el-menu加router,或者是menu-item没有绑定正确的index。而我这里给出的情况是:当我循环列表生成el-menu-item,他们之间使用id区分(或者是其他参数)。
如果el-menu的default-active="$route.name",因为他们的route.name相同,所以点击任意一项,el-menu-item会全部高亮。如果用$route.path,就会出现第一次点击不高亮,只有处于当前页面时,再次点击才会高亮。这时因为$route.path后面是没有参数的,这个值不等于el-menu-item的index(index是这个页面对应的完整路径,它是携带参数的)。
所以正确写法应该是:
<!-- 笔记:使用$route.fullPath使完整路径与menu-item的index属性相匹配。
该组件只有default-active的值与index相同时才能高亮,
因此在路径携带query参数的情况下,使用完整路径可以使路径+参数进行对比,保证选中项可以高亮。
注意因为是完整路径,前面要加上/符号。-->
<el-menu :default-active="$route.fullPath" class="el-menu-demo" mode="horizontal" :router="true">
<el-menu-item index="/Home">Home</el-menu-item>
<el-submenu index="/ProductList" ref="Product">
<template slot="title">Product</template>
<el-menu-item v-for="(item,index) in productionType" :key="index" :index="'/ProductList?id='+item.id" :route="{name:'ProductList',query: { id: item.id }, params: { adpic: item.adpic, imgPath: webpath,catname:item.catname,catjc:item.catjc}}">{{ item.catname }} {{'/ProductList?id='+item.id}}</el-menu-item>
</el-submenu>
<el-menu-item index="/ContactUs">Contact us</el-menu-item>
</el-menu>
如果无法解决问题,也欢迎评论区讨论