[Vuejs]-Vue router check if direct route

0👍

Found the answer in History Api

   const history = window.history.length;
   if (history > 2) {
      this.$router.go(-1);
    } else {
      this.$router.push(`/`);
    }

0👍

The history array is tight to the browser session history (that is, the pages visited in the tab or frame that the current page is loaded in) as per documentation.

This means that hard refreshes or direct navigations in the same tab will have the history array filled with previous entries. And the window.history.length check will fail.

Therefore I think the VUE way of detecting this would be using the navigation guards.

Before entering a new route, we can check if the previous URL is a known app route. And update a store property (directRoute here, that is defaulted to null) accordingly:

router.beforeEach((to, from, next) => {
    const previousRoutes = from.matched.length;
    const isJustLanding = store.state.directRoute === null && previousRoutes === 0;

    store.commit("updateDirectRoute", isJustLanding);

    next();
}

Leave a comment