Search code examples
vue.jsvue-componentvue-router

Check if there is a previous page in vue route


I am using $router.go(-1) to go back to the previous page but as I am using this on a home page I want know how to check if there is a previous route.


Solution

  • Vue router navigation is tracked by the native browser history, use window.history.length.

    If it is 0 there is nothing to go back to.

    However; Users arriving from another website have a value higher than 0.

    To overcome this issue, upon your App mounting; store the initial value of window.history.length globally.

    Capture the initial value using a mount hook such as: beforeMount or mounted.

    Store the history length value using $root as a global state:

    this.$root.historyCount = window.history.length
    

    Alternatively use VueX if you are already leveraging the store bus plugin.

    When checking history state on a call to action, subtract $root.historyCount from window.history.length to see if zeroes out.

    This way you will be only counting the history that occurs in your own app.

    You may also want to consider that perhaps if your current route ($router.currentRoute) is the home page there is also no way of going back beyond that page but obviously will prevent back navigation to prior home revisits.