Vue-Router是前台路由组件,Vue.js + Vue Router 创建单页应用,将自定义组件映射到Vue-Router中,由Vue-Router来渲染页面。
Vue-Router相关API参考https://router.vuejs.org/zh/api
<router-link to='/test'/> <!-- 路由组件的导航组件(用to属性设置跳转) -->
<router-view/> <!-- 路由组件的渲染组件 -->
this.$router <!-- 访问路由器 -->
this.$route <!-- 访问当前路由 -->
//路由组件根据网页请求路径来判断用path导航路径对应的组件渲染router-view
const router = new VueRouter({ //VueRouter是导入Vue-Router的别名 -->
routes: [
//path导航路径,component自定义组件(页面节点类似div,注意只能有一个根节点)
{path: '/:name/one', component: { template: '<div>foo</div>' }}, //动态路径/*/one
{path: '/:name/two', component: { template: '<div>{{$route.params.name}}</div>' }}, //$route获取当前路由
{path: '/redirect/test', redirect: '/redirect_test'}, //redirect重定向(可以是路径、路由器和方法)
{path: '/alias/test', component: { template: '<div>alias</div>' }, alias: '/alias_test'} //alias别名,功能效果不变,只替换URL显示
{
path: '/bar/three',
components: { //当一个导航组件对应多个渲染组件时,自定义组件别名与渲染组件name属性一一对应
a: {template: '<div>a template</div>'},
b: {template: '<div>b template</div>'}
},
children: [ //嵌套路由组件中的子路由(可多层嵌套)
{path: '/son', component: { template: '<div>son</div>'}}
]
}
]
})
//编程式导航(通常在Vue实例方法中使用)
this.$router.push(location, onComplete?, onAbort?) //路由导航方法(<router-link>导航组件后台调用的就是该方法)
location: 导航路径,通常直接使用字符串定义路径或使用name、params、path和query参数来搭配使用
onComplete: 导航成功时调用该方法(function)
onAbort: 导航失败时调用该方法(function)
this.$router.replace(location, onComplete?, onAbort?) //与push方法功能相同,区别在与该方法会替换当前历史记录
this.$router.go(n) //历史记录前进或者后退(正负数)
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => { //全局前置守卫(当一个导航触发时,全局前置守卫按照创建顺序调用)
//to 将进入的目标路由对象
//from 正要离开的路由对象
//next 页面跳转方法( next('/') 或 next({path: '/', name: 'abc'})可以定义router-link中的所有属性 )
})
router.beforeResolve((to, from, next) => { //全局解析守卫(导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用)
})
router.afterEach((to, from) => { //全局后置钩子(当一个导航触发后,全局后置钩子按照创建顺序调用,无法改变导航本身)
})
beforeEnter: (to, from, next) => { //路由独享前置守卫
}
beforeRouteEnter (to, from, next) { //组件守卫
// 在渲染该组件的对应路由被 confirm 前调用(不能获取组件实例`this`)
},
beforeRouteUpdate (to, from, next) { //组件守卫
// 在当前路由改变,但是该组件被复用时调用(可以访问组件实例 `this`)
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候调用
},
beforeRouteLeave (to, from, next) { //组件守卫
// 导航离开该组件的对应路由时调用(可以访问组件实例 `this`)
}