Vue学习:全局路由守卫beforeEach、afterEach

点---》会出现路由组件,但是有些组件---又特定要求才能显示组件---》在路由规则里面进行要求设置

创建路由

const router =  new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{title:'关于'}
        },....
}

对路由器+路由首位

全局前置路由守卫 ---》beforeEach--》初始化的时候被调用、每次路由切换之前被调用

/a 转换成为 /b 会调用 next()继续运行

接收三个参数起点from起点 to终点

router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫',to,from)
})

需要对路径进行判断

if(localStorage.to.path==='/home/news'||localStorage.to.path==='/home/message'

简化路径

if(localStorage.to.name==='xinwen'||localStorage.to.name==='xiaoxi'

但是当路径过多(给to里面+属性--你放的参数)

routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{title:'关于'}
        },

meta:{isAuth:true,title:'新闻'}

对这两个权限进行配置

if(to.meta.isAuth){ //判断是否需要鉴权
}
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫',to,from)
    if(to.meta.isAuth){ //判断是否需要鉴权
        if(localStorage.getItem('school')==='aaa'){
            next()
        }else{
            alert('学校名不对,无权限查看!')
        }
    }else{
        next()
    }
})

最后暴露

export default router

全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用 切换完成之后执行 没有next (切换完成后next不需要了)

为了在主页面显示--在后置 前置路由不可 因为你点击了路径变了。但实际上你没有登录进去

  document.title = to.meta.title || '系统'
router.afterEach((to,from)=>{
    console.log('后置路由守卫',to,from)
    document.title = to.meta.title || '系统'
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中使用路由的首位(beforeEach)钩子可以通过以下步骤实现: 1. 首先,安装 Vue Router。你可以通过在命令行中运行以下命令来安装它: ``` npm install vue-router ``` 2. 在你的应用程序的入口文件中(通常是 `main.js`),导入 Vue Router 并将其安装到 Vue 实例中: ```javascript import { createApp } from 'vue' import App from './App.vue' import router from './router' createApp(App).use(router).mount('#app') ``` 3. 创建一个名为 `router.js` 的新文件,并在其中定义你的路由配置和路由首位钩子: ```javascript import { createRouter, createWebHistory } from 'vue-router' import Home from './views/Home.vue' import About from './views/About.vue' const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About } ] const router = createRouter({ history: createWebHistory(), routes }) router.beforeEach((to, from, next) => { // 在这里进行路由首位的逻辑处理 // 比如检查用户是否已登录,如果未登录则重定向到登录页 next() // 必须调用 next() 方法以继续导航 }) export default router ``` 在 `beforeEach` 钩子函数中,你可以执行一些逻辑处理,例如检查用户是否已登录,根据需要进行重定向或其他操作。最后,必须调用 `next()` 方法以继续导航。 现在,你就可以在你的 Vue 组件中使用路由和这个路由首位钩子了。例如,在 `App.vue` 组件中可以添加以下内容: ```html <template> <div id="app"> <router-view></router-view> </div> </template> ``` 这样,你就可以根据定义的路由配置在不同的路由路径下展示相应的组件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值