Vue Shangpinhui Mall Project-day05 [36. Understanding of navigation guards]

insert image description here

36. Navigation guard understanding

Routing guards: divided into global guards, exclusive guards, and component guards.

  • Divided into global guards (commonly used): Once configured, the scope of action is all routes, which will be triggered as long as the route changes. Global routes are divided into global front guards and global post guards .
  • Exclusive guard (commonly used): It is called when entering the component. The difference is that if you want to control the authority of which route, you can directly add a guard to its route configuration item, and the ** scope is limited to the route. **Example: Assuming that the user has just successfully logged in, can he directly jump to the payment success page or the order page? The answer is no.
  • In-component guard (not commonly used): When using routing rules to enter or leave the component, the invocation of the guard in the component will be triggered, and the guard in the component is generally written inside the component, and its scope is limited to the component . For example: what happens before entering a certain room, and what happens after leaving, which is a bit similar to the back-end aspect, what happens before entering a method, and what happens after leaving a method.

Key and difficult points

  1. Understanding Navigation Guards
  1. Use navigation guards to implement the following functions

​ a. Only after logging in can you view the transaction/payment/personal center interface

​ b. You can view the login interface only if you have not logged in

c. Only the carried skuNum and skuInfo data in sessionStorage can view the interface of successfully adding to the shopping cart

​ d. You can only jump to the transaction interface from the shopping cart interface

​ e. You can only jump to the payment interface from the transaction interface

​ f. Only from the payment interface can you jump to the payment success interface

What is Navigation Guard?

1). Navigation guard is the following two functions provided by vue-router

​ a. Monitor routing jump --> callback function

​ b. Control routing jump

2). Application

​ a. Before jumping to the interface, perform user permission check restrictions (such as whether you have logged in)

​ b. Before leaving the interface, do the finishing work

Navigation guard classification

1). Global guard: jump for any route

​ a. Global pre-guard

​ b. Global rear guard

​ 2). Route exclusive guard

​ front guard

3). Component guard: only for the routing jump of the current component

a. to enter

b. Update

c. leave

Related APIs

1). Global front guard: before jumping to a routing component (used more in development)

​ router.beforeEach((to, from, next) => {// before enter each route component

​ …

​ })

​ Description:

​ ①.to: target route

​ ②. from: start route

③. next: function

​ next(): Execute the next guard callback, if there is no jump to the target route

​ next(false)/do not execute: the jump process is interrupted at the current position, and will not jump to the target routing component

​ next(path): Jump to another specified route

2). Global rear guard: after jumping to a routing component

​ router.afterEach((to, from) => {

​ })

3). Routing Exclusive Guard

​ beforeEnter: (to, from, next) => {

​ }

3). Component Guard

​ // Called before the current component object is created, cannot directly access this (not the component object)

​ // But you can access the component object in the callback function through next(component => {})

​ beforeRouteEnter (to, from, next) {

​ next(component => {})

​ },

​ // Called before the current component object is about to be updated, you can access this

​ beforeRouteUpdate (to, from, next) {

​ },

​ // Called before the current component leaves, you can access this

​ beforeRouteLeave (to, from, next) {

​ next()

​ }

Modify the code:

Delete trigger action in src/pages/Home/index.vue Home component

删除this.$store.dispatch('reqUserInfo');

src/router/index.js

let router = new VueRouter({
	...
})

//全局守卫:前置守卫(在路由跳转之间进行判断)
router.beforeEach(async (to, from, next) => {
    //to:获取到要跳转到的路由信息
    //from:获取到从哪个路由跳转过来来的信息
    //next: next() 放行  next(path) 放行  
    //获取仓库中的token-----可以确定用户是登录了
    let token  = store.state.user.token;
    let name = store.state.user.userInfo.name;
    //用户登录了
    if(token){
        //已经登录而且还想去登录------不行
        if(to.path=="/login"||to.path=='/register'){
            next('/');
        }else{
            //已经登陆了,访问的是非登录与注册
            //登录了且拥有用户信息放行
            if(name){
                next();
            }else{
                //登陆了且没有用户信息
                //在路由跳转之前获取用户信息且放行
                try {
                    await store.dispatch('reqUserInfo');
                    next();
                } catch (error) {
                    //token失效从新登录
                    await store.dispatch('reqLogout');
                    next('/login')
                }
            }
        }
    }else{
        //未登录:不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心
        //未登录去上面这些路由-----登录
        let toPath = to.path;
        if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
            //把未登录的时候向去而没有去成的信息,存储于地址栏中【路由】
            next('/login?redirect='+toPath);
        }else{
            //去的不是上面这些路由(home|search|shopCart)---放行
            next();
        }

    }
});

export default router;

src/pages/Login/index.vue

methods: {
    
    
      //登录的回调函数
      async reqUserLogin() {
    
    
        try {
    
    
           //成功
          const {
    
    phone, password} = this;
          phone && password && await this.$store.dispatch('reqUserLogin',{
    
    phone, password});
          //判断query是否有参数,有就登录后重定向
          let goPath = this.$route.query.redirect||'/home';
          //跳转到首页
          this.$router.push(goPath);
        } catch (error) {
    
    
           //失败
           alert(error.message)
        }
      }
    }

Note 1:

Question: What do to, from, next represent in the global component?

Answer:

  • to: Get the routing information to jump to
  • from: Get the information from which route to jump from
  • next: next() release next(path) release

Note 2: The logic of jump routing is very complicated, and the details are as follows:

  • Determine whether the user is logged in?

    • Logged in: Determine whether the jump route wants to go to ('/login') or ('/register')?

      • Yes: Prohibit jumping, and jump to the home page ('/')

      • Not: determine whether to have user information?

        • Yes: dispatch getUserInfo and release
        • None: dispatch userLogout and route to the login page ('/login')
    • Not logged in: Judging whether the jump route wants to go to transaction related ('/trade'), payment related ('/pay'), personal center related ('/center')

      • Yes: Prohibit redirection, and redirect to the login page ('/login')
      • not: let go

Note 3:

Question: How to set up routing guards?

Answer: It can be configured in src/router/index.js, but the original default export route is changed to first define the router variable to receive, then configure the route guard in the middle, and finally export the route.

Note 4:

Question: Why is there a redirect behind the login in else? What is it for?

Answer: There will be such a scenario requirement: before logging in, the default is to jump to the /home home page, and now there is a requirement: when the user is not logged in, click to jump to the order page -> first jump to the login page -> when logging in After success, it should jump to the order page instead of the home page, so this piece adds redirect and redirects to the desired location with the login method.

Links to my other related articles

1. Vue Shangpinhui mall project-day05 [30. Login and registration static components (handling public image resource issues) + 31. Registered business + login business] 2.
Vue Shangpinhui mall project-day05 [33. token order Brand understanding + 34. User login carries token to obtain user information + 35. Logout]
3. Vue Shangpinhui Mall project-day05 [36. Navigation guard understanding]

Supongo que te gusta

Origin blog.csdn.net/a924382407/article/details/129907725
Recomendado
Clasificación