vue实现路由组件
Vue 路由组件实现
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现路由组件的关键步骤:
安装 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'
const app = createApp(App)
app.use(router)
app.mount('#app')
路由视图和导航
在 App.vue 中:
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view/>
</div>
</template>
动态路由匹配
{
path: '/user/:id',
component: User,
props: true // 将路由参数作为 props 传递
}
导航守卫
router.beforeEach((to, from, next) => {
// 验证逻辑
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
嵌套路由
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
路由懒加载
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
编程式导航
// 字符串路径
router.push('/about')
// 带有路径的对象
router.push({ path: '/about' })
// 命名的路由
router.push({ name: 'About' })
// 带查询参数
router.push({ path: '/about', query: { id: 1 } })
// 带 hash
router.push({ path: '/about', hash: '#section' })
路由元信息
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true }
}
这些方法涵盖了 Vue Router 的基本使用场景,可以根据实际需求进行组合和扩展。







