当前位置:首页 > VUE

vue路由实现导航栏

2026-02-23 01:34:09VUE

实现导航栏的基本路由配置

在Vue项目中,使用vue-router实现导航栏功能需要先安装并配置路由。通过Vue CLI创建项目时可以选择包含vue-router,或者后续手动安装:

npm install vue-router

src/router/index.js中配置基本路由:

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

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

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

创建导航栏组件

新建src/components/NavBar.vue组件,使用<router-link>实现导航跳转:

<template>
  <nav>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
  </nav>
</template>

<style scoped>
nav {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background: #f0f0f0;
}
.router-link-active {
  font-weight: bold;
  color: #42b983;
}
</style>

在主应用中挂载路由和导航栏

src/App.vue中引入并使用导航栏组件:

<template>
  <NavBar />
  <router-view />
</template>

<script>
import NavBar from './components/NavBar.vue'

export default {
  components: { NavBar }
}
</script>

动态高亮当前路由链接

可以通过active-class属性自定义激活状态的类名,或使用exact-active-class精确匹配:

<router-link 
  to="/about" 
  active-class="active-link"
  exact-active-class="exact-active-link">
  About
</router-link>

编程式导航实现

除了<router-link>,也可以通过JavaScript实现导航跳转:

methods: {
  goToAbout() {
    this.$router.push('/about')
    // 或使用命名路由
    // this.$router.push({ name: 'About' })
  }
}

嵌套路由实现多级导航

对于复杂布局,可以配置嵌套路由:

const routes = [
  {
    path: '/user',
    component: UserLayout,
    children: [
      {
        path: 'profile',
        component: UserProfile
      },
      {
        path: 'settings',
        component: UserSettings
      }
    ]
  }
]

导航守卫控制访问权限

使用路由守卫实现权限控制:

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login')
  } else {
    next()
  }
})

响应式路由参数

在组件中访问动态路由参数:

export default {
  computed: {
    userId() {
      return this.$route.params.id
    }
  },
  watch: {
    $route(to, from) {
      // 对路由变化作出响应
    }
  }
}

vue路由实现导航栏

标签: 路由vue
分享给朋友:

相关文章

vue实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现类别

vue实现类别

Vue 实现类别的几种方法 在 Vue 中实现类别功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-bind:class 动态绑定类名 通过对象语法或数组语法动态绑定类名,根据条件添加或…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutat…

vue实现api

vue实现api

Vue 实现 API 调用 在 Vue 中调用 API 通常涉及使用 axios 或 fetch 发送 HTTP 请求,并结合 Vue 的响应式特性管理数据。以下是常见的实现方式: 安装 axi…

vue实现京东

vue实现京东

Vue 实现京东电商网站的关键步骤 项目搭建与基础配置 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 管理路由,Vuex/Pinia 管理状态。配置基础 UI 框架如 E…