Vue中点击导航链接更新数组current状态的最简解决方案
Vue导航栏激活状态修改最简方案
你的代码主要问题在于点击事件传递参数错误、激活判断逻辑有误,且未正确更新响应式数组。以下是最简修复方案:
1. 修正模板点击事件
把点击时传递的参数改为当前导航项的name,明确指定要激活的目标项:
<router-link v-for="item in navigation" :key="item.name" :to="item.to" @click="setCurrent(item.name)" :class="[item.current ? 'bg-gray-100 text-gray-900' : 'text-black hover:bg-gray-50 hover:text-gray-900', 'group flex items-center px-2 py-2 text-base font-medium rounded-md']"> <component :is="item.icon" :class="[item.current ? 'text-black' : 'text-black group-hover:text-gray-500', 'mr-4 h-6 w-6 router-link']" aria-hidden="true" /> {{ item.name }} <LockClosedIcon v-if="item.locked" :class="['ml-16 items-end rounded-full bg-pink-100 px-0.9 py-0.5 text-pink-800 w-6 h-6']"/> </router-link>
2. 重写setCurrent方法
直接遍历导航数组,重置所有项的current为false,再将目标项的current设为true——Vue会自动响应对象属性的修改,无需额外操作:
export default{ data() { return { sidebarOpen: false, displayUserName: store.user.username, navigation : [ { name: 'Dashboard', to: '/dash/Home', requiresSecondaryBar: true,icon: HomeIcon, current: true, locked: false }, { name: 'My courses', to: '/dash/MyCourses', requiresSecondaryBar: true,icon: CalendarIcon, current: false, locked: !store.details.hasCourse }, { name: 'Courses', to: '/dash/Courses', requiresSecondaryBar: false,icon: UserGroupIcon, current: false, locked: false}, { name: 'Messages', to: '/dash/Messages', requiresSecondaryBar: true,icon: MagnifyingGlassCircleIcon, current: false, locked: false }, { name: 'Community', to: '/dash/Community', requiresSecondaryBar: true,icon: MegaphoneIcon, current: false, locked: false}, { name: 'Resources', to: '/dash/Resources', requiresSecondaryBar: true,icon: MapIcon, current: false, locked: false }, { name: 'Flip', to: '/dash/Flip', requiresSecondaryBar: false,icon: MapIcon, current: false, locked:false }, ] } }, methods: { setCurrent(activeName) { this.navigation.forEach(item => { item.current = item.name === activeName; }); } } }
原代码核心问题梳理
- 点击事件传递
true无法区分目标项,导致无法精准激活; checkCurrent方法逻辑错误:this.navigation是数组,不存在name属性,且误用赋值运算符=而非全等比较===;- 原
setCurrent用map生成新数组但未赋值回this.navigation,原响应式数组未更新,视图不会变化; - 原
map中修改了to属性路径,导致部分路由跳转错误(比如Dashboard原路径/dash/Home被改成/dash/Dashboard)。
内容的提问来源于stack exchange,提问作者DMantas
相关产品推荐
相关产品推荐

