Detect Back Button in Navigation Guards of Vue-Router

前端 未结 3 1542
故里飘歌
故里飘歌 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:09

    This is done very easily.

    const router = new VueRouter({
      routes: [...],
      scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
          // History back position, if user click Back button
          return savedPosition
        } else {
          // Scroll to top of page if the user didn't press the back button
          return { x: 0, y: 0 }
        }
      }
    })
    

    Check here: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

    0 讨论(0)
  • 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()
    })
    
    0 讨论(0)
  • 2020-12-06 20:31

    This is the only way that I've found:

    We can listen for popstate, save it in a variable, and then check that variable

    // This listener will execute before router.beforeEach only if registered
    // before vue-router is registered with Vue.use(VueRouter)
    
    window.popStateDetected = false
    window.addEventListener('popstate', () => {
      window.popStateDetected = true
    })
    
    
    router.beforeEach((to, from, next) => {
      const IsItABackButton = window.popStateDetected
      window.popStateDetected = false
      if (IsItABackButton && from.meta.someLogica) {
        next(false) 
        return ''
      }
      next()
    })
    
    0 讨论(0)
提交回复
热议问题