You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3实现带左侧圆角边框的激活态侧边导航

Vue3 侧边导航Active状态左侧圆角边框实现方案

核心思路

用::before伪元素模拟左侧带圆角的高亮边框,通过绝对定位控制伪元素的位置和尺寸,结合导航项的相对定位与溢出隐藏,实现目标效果。直接使用border-left无法单独给边框设置上下圆角,伪元素是更灵活的方案。

完整实现代码

SideBar.vue

<template>
  <div class="sidebar">
    <router-link 
      v-for="route in navRoutes" 
      :key="route.path" 
      :to="route.path"
      class="sidebar-item"
    >
      {{ route.meta.title }}
    </router-link>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
// 过滤出带导航标题的路由
const navRoutes = router.options.routes.filter(r => r.meta?.title)
</script>

<style scoped>
.sidebar {
  width: 220px;
  background: #f6f8fa;
  padding: 16px 0;
}

.sidebar-item {
  display: block;
  padding: 14px 24px;
  color: #2c3e50;
  text-decoration: none;
  position: relative; /* 为伪元素提供定位基准 */
  overflow: hidden; /* 防止伪元素超出导航项边界 */
  transition: background 0.2s ease;
}

.sidebar-item:hover {
  background: #eef2f7;
}

/* Active状态的左侧圆角边框 */
.sidebar-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 8px; /* 上下预留间距,让圆角可见 */
  bottom: 8px;
  width: 4px; /* 边框宽度 */
  background: #2563eb; /* 高亮颜色 */
  border-radius: 0 4px 4px 0; /* 右侧圆角,对应视觉上的左侧圆角效果 */
}
</style>

router.js 配置(关键:指定active类名)

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Dashboard from '../views/Dashboard.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '首页' }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { title: '控制台' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  linkActiveClass: 'active' // 绑定自定义的active类
})

export default router

常见问题排查

  1. 伪元素不显示:检查是否添加了content: '',导航项是否设置了position: relative,伪元素的宽度、背景色是否正确。
  2. 圆角不明显:调整top和bottom的值,让伪元素与导航项上下边缘保留一定间距,圆角才会显现。
  3. active类未生效:通过浏览器开发者工具检查当前路由的导航项是否被添加了active类,若未生效,确认router配置中linkActiveClass是否正确设置。

内容的提问来源于stack exchange,提问作者Sarwan gds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:05:26