How to handle anchors (bookmarks) with Vue Router?

Viewed 31074

I'm looking for a smart way to handle in-page anchors with Vue Router. Consider the following:

<router-link to="#app">Apply Now</router-link>
<!-- some HTML markup in between... -->
<div id="app">...</div>

The "scroll to anchor" behavior described in the docs works fine except:

  • When you click on the anchor, it brings you down to the div id="app". Now scroll away from the div back to the anchor and try clicking it again -- this time you will not jump down to the div. In fact, the anchor will retain the class router-link-active and the URL will still contain the hash /#app;
  • With the steps above, if you refresh the page (the URL will still contain the hash) and click on the anchor, nothing will happen either.

This is very unfortunate from the UX perspective because a potential customer has to manually scroll all the way down again to reach the application section.

I was wondering if Vue Router covers this situation. For reference, here's my router:

export default new VueRouter({
    routes,
    mode: 'history',
    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return { selector: to.hash }
        } else if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 }
        }
    }
})
5 Answers

If you're already on the route with the hash, you can just set it to scroll to the target.

(also note scrollBehavior() method in your router won't get called if you're already on the route you're trying to go to).

export default {
  methods: {
    anchorHashCheck() {
      if (window.location.hash === this.$route.hash) {
        const el = document.getElementById(this.$route.hash.slice(1))
        if (el) {
          window.scrollTo(0, el.offsetTop)
        }
      }
    },
  },
  mounted() {
    this.anchorHashCheck()
  },
}

Then add a @click.native to listen to events on the anchor in your <router-link>,

<router-link :to="{hash: '#some-link'}" @click.native="anchorHashCheck">
  Some link
</router-link>

I realize you asked about anchors and you have an answer already. However, the below function should work for both anchors and regular links. It allows you to scroll to the position of the first instance of the Component a Route has been matched to. I wrote it to see if I could by-pass using a hash while retaining anchor-style scrolling.

scrollBehavior(to, from, savedPosition) {
  if (to.matched) {
    const children = to.matched[1].parent.instances.default.$children;
    for (let i = 0; i < children.length; i++) {
      let child = children[i];
      if (child.$options._componentTag === to.matched[1].components.default.name) {
        return {
          x: child.$el.offsetLeft,
          y: child.$el.offsetTop
        };
      }
    }
  }
  return {
    x: 0,
    y: 0
  };
}

The reason I'm using parent.instances is because the to.matched[1].instances value is empty. It's not the most elegant solution, though it might help someone else out there.

Note: This only works when you want to scroll the first instance of a Component.

Related