vueRouter一般只在项目开始时配置,跳转方式常用的也就那两三种,避免每次遇到问题翻好久官方文档,所以在此记录常用方法:
基本使用
<div id="app>
<router-link to="/bar">Go to Bar</router-link>
<router-view></router-view>
</div>
<script>
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{path: '/bar', component: Bar }
]
})
new Vue({ router })
</script>
动态路由匹配
// 路由参数 this.$route.params.id 999
<router-link to="/foo/999">Go to Foo</router-link>
{path: '/foo/:id', component: Foo}
// 路由参数变化监视
watch:{
'$route'(to, from) {}
}
beforeRouteUpdate (to, from, next) {}
嵌套路由
const User = {
template: `<div>User:
<router-link to="/one">Go to one</router-link>
<router-link to="/two">Go to two</router-link>
<router-view></router-view>
</div>`,
}
const routes = [
{
path: '/user',
component: User,
children: [
{path: '/one', component: One},
{path: '/two', component: Two},
]
}
]
命名路由
{path: '/bar/:id', component: Bar, name: 'newbar'}
<router-link :to="{ name: 'newBar', params: { id: 123 }}">bar</router-link> // 声明式
this.$router.push({ name: 'newBar', params: { id: 123 }}) // 编程式
编程式导航
this.$router.push('/bar') //字符串
this.$router.push({path: '/bar'}) //对象
this.$router.push({path: '/bar/123'}) // 完整路径 /bar/123
this.$router.push({ name: 'newbar', params: { id: 123 }})
// 命名的路由 /bar/123
this.$router.push({ path: 'bar', query: { plan: 'private' }})
// 带查询参数,变成 /bar?plan=private
this.$router.go(n) // 在 history 记录中向前或者后退n步
命名视图
<router-view></router-view>
<router-view name="one"></router-view>
// 和slot的name差不多
const routes = [
{
path: '/',
components: {
default: Default,
one: One
}
}
]
重定向: redirect
别名: alias
History模式:mode: 'history’
路由组件传值
const Foo = {
template: `<div>Foo {{id}}</div>`,
props: ['id'] // this.$route.params.id
}
const routes = [
{
path: '/foo/:id',
component: Foo,
props: true
}
]
// 布尔
props: true/false
// 对象
props: {id: XXX}
// 函数
props: route => {
return { id: route.parame.id }
}
导航守卫
// 全局守卫App
router.beforeEach((to, from, next) => {}) //进入路由前
router.beforeResolve(to, from, next) => {}) //组件守卫和异步路由守卫解析
router.afterEach(to, from) => {}) //进入路由后
// 路由配置 routes数组对象里面配置
beforeEnter: (to, from, next) => {}) //相同路由触发一次
// 组件内的守卫component
beforeRouteEnter (to, from, next) {} // 进入导航之前 不能获取this
beforeRouteUpdate (to, from, next){} // 组件复用,路由改变
beforeRouteLeave (to, from, next) {} // 导航离开
完整的导航解析流程 (导航A切换到导航B)
- 导航被触发。
- 在失活的组件里调用离开守卫。(A组件内beforeRouteLeave)
- 调用全局的 beforeEach 守卫。
- 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。 (AB如果是重用组件则调用)
- 在路由配置里调用 beforeEnter。
- 解析异步路由组件。
- 在被激活的组件里调用 beforeRouteEnter。(B组件)
- 调用全局的 beforeResolve 守卫 (2.5+)。
- 导航被确认。
- 调用全局的 afterEach 钩子。
- 触发 DOM 更新。