vue中的全局解析守卫有什么作用?

2021-02-01 09:49发布

6条回答
studentaaa
2021-02-02 11:07

在实际项目中,路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。举个例子,我们通常使用 router.beforeEach 注册一个全局前置守卫用来判断登录的状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
let routesArr = [{
        path: '/home',
        name:"home",
        //redirect:"/about",//重定向
        //alias: '/index',//别名
        component: {
        template: `
                

这是首页

                        
`              
            }
            }, {
            path: '/about',
            name:'about',
            component: {
            template: `
                            

这是关于我们页

                        
`
            }
                    }, {
            path: '/user/:name'// :name的作用是动态访问一个地址,比如传进来的是张三,就显示张三的信息
            name: 'user'// 这个name的作用是配合第95行添加属性用的,二者必须一致
            component: {
            template: `
 
                            
                            

我叫:{{ $route.params.name }}

 
                            
                            

我今年:{{ $route.query.age }} 岁了

 
                            
                                
                                "more" append> 更多信息
                            
                             
                            
                            
                        
`
                },
                children: [{
                path: 'more',
                component: {
                template: `
                                
                                用户:{{ $route.params.name }} 的详细信息 abcd1234
                                
`
                }
                }]
                }
 
                ];
 
                const vRouter = new VueRouter({
                    routes: routesArr // 这里要写routes ,而不是routers,不然 没数据
                })

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vRouter.beforeEach((to, from, next) => {
    //这里写你的判断逻辑
    const nextRoute = ['home''good-list''good-detail''cart''profile'];//需要登陆的页面名
    let isLogin=  localEvent.get('web_login')||false;//获取是否登录状态
    // 未登录状态;当路由到nextRoute指定页时,跳转至login
    if (nextRoute.indexOf(to.name) > -1) { 
      if (!isLogin) {
        //router.push({ name: 'login' });//可以直接跳转名
        //next({ path: '/login', query: { redirect: to.fullPath } });//也可以跳转路径,并带上重定向
      }
    }
    // 已登录状态;当路由到login时,跳转至home
    if (to.name === 'login') {
      if (isLogin) {
        router.push({ name: 'home' });
      }
    }
    next();
});



一周热门 更多>