Detect Back Button in Navigation Guards of Vue-Router

前端 未结 3 1557
故里飘歌
故里飘歌 2020-12-06 19:53

How the route is changed, matters for my case. So, I want to catch when the route is changed by a back button of browser or gsm.

This is what I have:



        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 20:21

    As stated by @Yuci, all the router hook callbacks are performed before popstate is updated (and therefore not helpful for this use case)

    What you can do:

    methods: {
        navigate(location) {
            this.internalNavigation = true;
            this.$router.push(location, function () {
                this.internalNavigation = false;
            }.bind(this));
        }
    }
    
    1. Wrap 'router.push' with you own 'navigate' function
    2. Before calling router.push, set 'internalNavigation' flag to true
    3. Use vue router 'oncomplete' callback to set internalNavigation flag back to false

    Now you can check the flag from within beforeEach callback and handle it accordingly.

    router.beforeEach((to, from, next) => {
      if ( this.internalNavigation ) {
          //Do your stufff
      }
      next()
    })
    

提交回复
热议问题