初始化 vur-router
router/index.js
- 注册路由插件
// Vue.use() 用于注册插件,如果传入的参数是一个方法时,直接执行方法,如果传入的参数是一个对象,则调用传入对象的install方法
Vue.use(VueRouter)
- 书写路由规则
const routes = [
{
path: '/',
name: 'Index',
component: Index
},
{
path: '/blog',
name: 'Blog',
component: () => import('../views/Blog.vue')
},
...
]
- 创建 router 对象并导出
const router = new VueRouter({
routes
})
export default router
main.js
- 注册 router 对象
new Vue({
router,
render: h => h(App)
}).$mount('#app')
注册 router 会在创建出来的 Vue 实例上添加上 $route 和 $router 两个属性:
$route中存储了当前路由的一些数据。$router就是我们的VueRouter实例,在这个实例上提供了一些路由相关的方法和信息,其中的currentRoute属性就是对应$route。
App.vue
- 创建路由组件的占位
<router-view> - 创建链接
<router-link>
<div id="nav">
<router-link to="/">Index</router-link> |
<router-link to="/blog">Blog</router-link> |
...
</div>
<router-view/>
动态路由
router/index.js 中设置动态路由
const routes = [
...
{
// :id 就是动态路由,用一个占位符匹配url
path: '/detail/:id',
name: 'Detail',
// 开启 props,会把 URL 中的参数传递给组件,在组件中通过 props 来接收 URL 参数
props: true,
// 采用的路由懒加载,当访问这个路由地址的时候才会加载对应的组件
component: () => import('../views/Detail.vue')
}
]
Detail.vue 中获取动态路由
// Detail.vue
<template>
<div>
<!-- 方式1: 通过当前路由规则,获取数据 -->
通过当前路由规则获取:{{ $route.params.id }}
<br>
<!-- 方式2:路由规则中开启 props 传参 -->
通过开启 props 获取:{{ id }}
</div>
</template>
<script>
export default {
name: 'Detail',
// 接收动态路由和父子组件传值一样,使用 props
props: ['id']
}
</script>
嵌套路由
const routes = [
{
name: 'login',
path: '/login',
component: Login
},
// 嵌套路由
{
path: '/',
component: Layout,
// 最后的地址就是 path 拼接子路由的 path,先加载 Layout 组件再加载子路由的组件
children: [
{
name: 'index',
path: '',
// path: '/',这里可以写绝对路径和相对路径,都是可以的
component: Index
},
{
name: 'detail',
path: 'detail/:id',
// path: '/detail/:id',
props: true,
component: () => import('@/views/Detail.vue')
}
]
}
]
编程式导航
push
// 使用字符串
this.$router.push('/')
// 使用命名式导航,导航的 name 是在路由规则中配置的
this.$router.push({ name: 'Home' })
// 导航到动态路由
this.$router.push({ name: 'Detail', params: { id: 1 } })
replace
this.$router.replace('/login')
go
this.$router.go(-2)