简介:
Vue 是一种流行的 JavaScript 框架。Vue 是一个可扩展的 MVVM 框架,它可以轻松创建可重用和可扩展的组件。Vue Router 是一个官方的 Vue.js 路由管理器。Vue.js 路由器允许您通过路由器将 URL 映射到应用程序的组件层次结构。
多级标题:
一、关于 Vue Router
二、安装和导入 Vue Router
三、Vue Router 基础
四、Vue Router 组件
五、嵌套路由
六、参数传递
七、重定向和别名
八、路由中间件
内容详细说明:
一、关于 Vue Router:
Vue Router 是 Vue.js 官方提供的路由管理器。路由管理器允许您通过路由将 URL 映射到应用程序的继承层次结构。Vue Router 帮助用户将应用程序状态组件化,从而轻松处理跳转和其他路由相关行为。
二、安装和导入 Vue Router:
要使用 Vue Router,需要在项目中安装 Vue Router ,可以使用npm或者yarn来安装
``` npm install vue-router```
安装完成后即可将 Vue Router 引入 Vue 应用程序的主要 JS 文件中:
```import VueRouter from 'vue-router'```
三、Vue Router 基础:
Vue Router 允许您定义路由和路由组件。路由是 URL 和组件之间的映射。在 Vue Router 中定义路由是通过一个新的 VueRouter 实例完成的。
定义路由:
```
const router = new VueRouter({
routes: [
// 定义路由
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/contact',
component: Contact
}
]
})
```
配置 mode: ‘history’ ,URL 将不会有 # 号,例如 http://localhost:8080/home 。
```
const router = new VueRouter({
mode: 'history',
routes: [....],
})
```
四、Vue Router 组件:
定义一个组件是通过 Vue.extend() 方法实现的。Vue Router 使您能够将组件与路由关联起来,这样当某个路由被访问时,将自动渲染相应的组件。
```
import Home from './components/Home.vue'
import About from './components/About.vue'
import Contact from './components/Contact.vue'
const router = new VueRouter({
routes: [
// 定义路由
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/contact',
component: Contact
}
]
})
```
五、嵌套路由:
Vue Router 还支持嵌套路由。通过这种方式,您可以将多个组件嵌套在一起,并将各自的路由与其关联。
```
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
component: Dashboard,
children: [
{
path: 'home',
component: Home
},
{
path: 'about',
component: About
},
{
path: 'contact',
component: Contact
}
]
}
]
})
```
六、参数传递:
在 Vue Router 中,您可以以两种方式传递参数。第一种是在路由中设置动态参数,第二种是在 URL 查询字符串中传递参数。
在路由中设置动态参数:
```
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: User,
props: true
}
]
})
```
通过这种方式定义路由相当于给路由添加了一个参数 id,这样就可以在组件中使用该参数。
七、重定向和别名:
Vue Router 还支持重定向和别名。重定向让您可以将一个 URL 重定向到另一个位置,而别名则让您可以在不改变 URL 的情况下将组件映射到某个位置。
重定向:
```
const router = new VueRouter({
routes: [
{
path: '/home',
redirect: '/'
}
]
})
```
别名:
```
const router = new VueRouter({
routes: [
{
path: '/home',
component: Home,
alias: '/alias'
}
]
})
```
八、路由中间件:
Vue Router 还支持路由中间件。这种方式非常有用,可以帮助您在路由中添加逻辑,例如身份验证或模板导航。中间件是在路由中添加的函数。在 Vue Router 中,中间件可以被定义为单独的路由或作为全局路由。
定义全局路由中间件:
```
const router = new VueRouter({
routes: [...],
})
router.beforeEach((to, from, next) => {
// 跳转到登录页面要检查是否已经登录
if (to.path === '/login' && store.getters.loggedIn) {
next('/')
} else {
next()
}
})
```