Search code examples
javascripthtmlvue.jsvue-routerhtml5-history

How can I detect a Vue $router.back() is done, rather than the case of empty history stack?


I'm using Vue with VueRouter.

And there is a back button on my page, I'm now setting the @click action to do $router.back().

<a class="btn-back" @click="$outer.back()"></a>

But if the page is opened directly (without a previous history url), nothing happend.

In this case, I want the page replace to a specific location (home page for example). How can I do that?

I've been looked for the techique to tell if the history is empty with no luck.


Solution

  • Finally I found a tricky way to do this.

    Actually, if there is some other previous page in the history stack, after we call $router.back(), the route info should have been changed.

    So, we can check the route and tell if the route is changed, after $router.back. If the route is not changed, it means the history stack is empty, then we do the $router.replace() instead.

    Overall, I wrote such a method:

    import _ from 'lodash'
    
    export default {
      // ...
      methods: {
        backOrRedirect (route) {
          const vm = this
          const originRoute = { ...vm.$route }
          vm.$router.back()
          // Of course, we must detect until a $nextTick is reached
          vm.$nextTick(() => {
            // If the route is not changed, we do the redirect
            if (_.isEqual(originRoute, vm.$route)) {
              // Redirect to the home path by default
              vm.$router.replace(route || '/')
            }
          })
        }
      }
      // ,,,
    }
    

    I use lodash to compare between the origin route and the newRoute object.

    So, we can easily call vm.backOrRedirect(url) to launch a $router.back(), which will definitely fall back to redirect to some page when the history stack is empty.