Remember position history and navigate to anchors in Vue

You can remember the position in a view and navigate users to that position when they click on ‘back’. You could also navigate users to specific anchor links in a long page.

Vue is a great single page app. Navigation between views is almost seamless and feels really fast. This magic of front-end routing is enabled by Vue router.

A simple router code-fragment looks like this -

// src/router.js

import Router from "vue-router";
// ...
Vue.use(Router);

export default new Router({
  // ...
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/profile",
      name: "profile",
      component: () => import("./views/Profile.vue")
    },
    {
      path: "/contact",
      name: "contact",
      component: () => import("./views/Contact.vue")
    }
  ]
});

To navigate from one page to the other, you simply do -

<router-link :to="{ name: home }">Home</router-link>

How does this navigation work if the home page has a bunch of anchor links?

Well, you could always use the simple <a id="footer"> to scroll to the footer. This will work perfectly when you are on the home page, but does not directly work with router-link.

But, what if the user -

  • clicks on a link after reading 3/4th of your beautifully written text
  • clicks on ‘back’ button

The user lands on the beginning of the page in history - which can be a problem. Ideally they need to be navigated to the position that they were at previous to clicking on the super-clickable link.

You accomplish the above described navigation with two steps in Vue.

Add hash

You simply add hash to router-link knows to navigate to a link and to a specific anchor element.

<router-link :to="{ name: home, hash: '#footer' }">
  Home Footer
</router-link>

Change router to scroll to position or anchors

Hash by itself will change the URL to include the specific anchor in URL. We also have the problem of navigating to previously remembered position if user comes to this page through back button.

We accomplish both of the above requirements by scrolling to either the specified anchor or to the previously remembered position. We do this by changing the router.

// src/router.js

// ...

export default new Router({
  // ...
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    }
    // ...
  ],

  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { selector: to.hash };
    }
    return { x: 0, y: 0 };
  }
});

Vue makes life real easy, doesn’t it?

comments powered by Disqus