马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
一、全局路由保卫 router.js
1. 前置保卫
- router.beforeEach((to, from, next) => {
- // to: Route 即将要进入的目标 路由对象
- // from: Route 当前导航正要离开的路由
- // next: Function 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
-
- // 例如,验证用户是否已登录
- if (to.matched.some(record => record.meta.requiresAuth)) {
- if (!auth.isLoggedIn()) {
- next({
- path: '/login',
- query: { redirect: to.fullPath }
- });
- } else {
- next();
- }
- } else {
- next(); // 确保一定要调用 next()
- }
- });
复制代码 2. 后置钩子
- router.afterEach((to, from) => {
- // to: Route 即将要进入的目标 路由对象
- // from: Route 当前导航正要离开的路由对象
- // 全局后置钩子,不会接受 next 函数也不会改变导航本身
- if (to.meta.title) {
- document.title = to.meta.title + " - 系统名称"
- }
- console.log('Navigation completed successfully.');
- });
复制代码 二、路由独享的保卫
- const router = new VueRouter({
- routes: [
- {
- path: '/foo',
- component: Foo,
- beforeEnter: (to, from, next) => {
- // 参数和全局前置守卫类似
- }
- }
- ]
- });
复制代码 三、组件内的保卫
可以在路由组件内直接定义以下三个路由保卫:
- beforeRouteEnter
- beforeRouteUpdate (2.2+ 支持)
- beforeRouteLeave
复制代码 示例:beforeRouteEnter 保卫
- export default {
- name: 'UserProfile',
- beforeRouteEnter(to, from, next) {
- // 在渲染该组件的对应路由被 confirm 前调用
- // 不能获取组件实例 `this` 组件实例尚未创建
- next(vm => {
- // 通过 `vm` 访问组件实例
- });
- },
- beforeRouteLeave(to, from, next) {
- // 导航离开该组件的对应路由时调用
- // 可以访问组件实例 `this`
- const answer = window.confirm('Do you really want to leave? you have unsaved changes!');
- if (answer) {
- next(); // 确保调用 next() 方法,否则钩子就不会被 resolved。
- } else {
- next(false); // 使用 'next(false)' 来取消导航并停留在当前页面。或者可以使用 'next('/')' 或者 'next(new Location)' 来跳转到不同的地址。
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |