当前位置:首页 > VUE

vue实现侧部导航

2026-01-18 07:24:38VUE

使用 Vue Router 实现侧部导航

在 Vue 项目中,侧部导航通常结合 Vue Router 实现路由跳转。通过配置路由表,动态生成导航菜单。

路由配置示例

const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/about', name: 'About', component: About },
  { path: '/contact', name: 'Contact', component: Contact }
]

导航组件模板

<template>
  <div class="sidebar">
    <router-link 
      v-for="route in routes" 
      :key="route.path" 
      :to="route.path"
      active-class="active"
    >
      {{ route.name }}
    </router-link>
  </div>
</template>

使用递归组件实现多级导航

对于多层级菜单,可采用递归组件实现。

递归组件示例

<template>
  <ul>
    <li v-for="item in menuItems" :key="item.path">
      <router-link :to="item.path">{{ item.title }}</router-link>
      <menu-tree v-if="item.children" :menuItems="item.children"/>
    </li>
  </ul>
</template>

<script>
export default {
  name: 'MenuTree',
  props: ['menuItems']
}
</script>

结合状态管理控制导航折叠

使用 Vuex 或 Pinia 管理导航栏的展开/折叠状态。

vue实现侧部导航

状态管理示例

// store.js
export const useAppStore = defineStore('app', {
  state: () => ({ isCollapse: false }),
  actions: {
    toggleCollapse() { this.isCollapse = !this.isCollapse }
  }
})

组件中使用

<template>
  <button @click="store.toggleCollapse">
    {{ store.isCollapse ? '展开' : '折叠' }}
  </button>
  <div :class="['sidebar', { 'collapsed': store.isCollapse }]">
    <!-- 导航内容 -->
  </div>
</template>

响应式设计处理

通过 CSS 媒体查询实现移动端适配。

响应式样式示例

vue实现侧部导航

.sidebar {
  width: 250px;
  transition: width 0.3s;
}

@media (max-width: 768px) {
  .sidebar {
    width: 80px;
  }
}

.collapsed {
  width: 64px;
}

动态权限控制导航显示

根据用户权限过滤导航菜单项。

权限过滤示例

const filteredRoutes = computed(() => {
  return routes.filter(route => {
    return userPermissions.includes(route.meta?.permission)
  })
})

使用第三方 UI 库

可选用现成的 UI 组件库快速实现:

  • Element Plus 的 el-menu 组件
  • Ant Design Vue 的 a-menu 组件
  • Vuetify 的 v-navigation-drawer 组件

Element Plus 示例

<el-menu :collapse="isCollapse">
  <el-submenu v-for="item in menuData" :key="item.id">
    <template #title>{{ item.title }}</template>
    <el-menu-item 
      v-for="child in item.children" 
      :key="child.path" 
      :index="child.path"
    >
      {{ child.title }}
    </el-menu-item>
  </el-submenu>
</el-menu>

标签: vue
分享给朋友:

相关文章

vue   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue 实现pdf

vue 实现pdf

在Vue中实现PDF功能 在Vue项目中实现PDF功能通常涉及PDF生成、预览或下载。以下是几种常见实现方式: 使用vue-pdf库预览PDF 安装依赖: npm install vue-pdf…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

vue实现setinterval

vue实现setinterval

在 Vue 中使用 setInterval Vue 中可以通过生命周期钩子和方法结合 setInterval 实现定时任务。以下是一个完整的实现示例: <template> <…

vue实现返回

vue实现返回

返回按钮功能实现 在Vue中实现返回功能通常有两种方式:使用浏览器历史记录的history.back()或结合Vue Router进行编程式导航。以下是具体实现方法: 使用浏览器API metho…

vue实现看板

vue实现看板

Vue 实现看板功能 使用 Vue 实现看板功能可以通过组件化开发、状态管理和拖拽库结合完成。以下是一个完整的实现方案: 基础项目结构 src/ ├── components/ │ ├── Ka…