利用vue实现导航
使用 Vue 实现导航
基于 Vue Router 的基本导航实现
安装 Vue Router 依赖
npm install vue-router
创建路由配置文件
// 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
在主应用中注册路由
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
导航菜单组件实现
创建导航菜单组件
<!-- components/Navigation.vue -->
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</template>
在应用中使用导航组件

<!-- App.vue -->
<template>
<Navigation />
<router-view />
</template>
<script>
import Navigation from './components/Navigation.vue'
export default {
components: {
Navigation
}
}
</script>
动态导航实现
创建动态路由配置
// router/index.js
const routes = [
// ...其他路由
{
path: '/products/:id',
name: 'Product',
component: () => import('../views/Product.vue')
}
]
动态导航链接实现
<template>
<router-link
v-for="product in products"
:key="product.id"
:to="'/products/' + product.id"
>
{{ product.name }}
</router-link>
</template>
<script>
export default {
data() {
return {
products: [
{ id: 1, name: 'Product 1' },
{ id: 2, name: 'Product 2' }
]
}
}
}
</script>
导航守卫实现
全局前置守卫

// router/index.js
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next('/login')
} else {
next()
}
})
路由独享守卫
{
path: '/profile',
name: 'Profile',
component: Profile,
beforeEnter: (to, from, next) => {
if (!isAuthenticated()) {
next('/login')
} else {
next()
}
}
}
响应式导航实现
响应式导航菜单
<template>
<button @click="toggleMenu">Menu</button>
<nav :class="{ 'active': menuActive }">
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</template>
<script>
export default {
data() {
return {
menuActive: false
}
},
methods: {
toggleMenu() {
this.menuActive = !this.menuActive
}
}
}
</script>
<style scoped>
nav {
display: none;
}
nav.active {
display: block;
}
</style>
嵌套路由实现
嵌套路由配置
const routes = [
{
path: '/user',
component: UserLayout,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'settings',
component: UserSettings
}
]
}
]
嵌套路由视图
<!-- UserLayout.vue -->
<template>
<div>
<h2>User</h2>
<router-view />
</div>
</template>






