How to anchor to div within the same Vue.js component?

Sometimes, we want to anchor to div within the same Vue.js component.

In this article, we’ll look at how to anchor to div within the same Vue.js component.

How to anchor to div within the same Vue.js component?

To anchor to div within the same Vue.js component, we can create a method that calls scrollTo to scroll to the element’s position.

For instance, we write

<template>
  <div id="app">
    <a @click="scrollMeTo('porto')">Porto, Portugal</a>
    ...
    <div ref="porto">...</div>
    ..
  </div>
</template>

<script>
//...
export default {
  //...
  methods: {
    scrollMeTo(refName) {
      const element = this.$refs[refName];
      const top = element.offsetTop;
      window.scrollTo(0, top);
    },
  },
  //...
};
</script>

to add an anchor element that calls the scrollMeTo method with the ref name of the element we want to scroll to on click.

Then in the scrollMeTo method, we get the refName parameter value and use that to get the element from this.$refs.

And then we get the top of the element with element.offsetTop.

Finally, we call window.scrollTo with 0 and top to scroll to the top of the element.

Conclusion

To anchor to div within the same Vue.js component, we can create a method that calls scrollTo to scroll to the element’s position.