[Vuejs]-How to route to specific div in a component in vuejs 2

0👍

Let’s say you want to bring in focus to a specific div in the Service component.

we will make use of query params to achive this. You add add a dedicated url as well which will do this.

This is my route:

{
    path: '/services',
    name: 'services',
    component: Services
}

Then in the url localhost:8000/services?show=mydiv and in the mounted hook of the component do something like this:

mounted() {
  // add a id to the div we want to bring in foucs
  // and id and the id is paased the query params
  document.getElementById(this.$route.query.show).scrollIntoView()
}

Let me know if it works for you.

Edit

Another way we can make this work is by using a watcher and a computed property.

First add a computed property for the show query param in the route.

computed: {
  show() { return this.$router.query.show }
}

Then add a watcher to trigger the focus.

watch: {
  show: {
    immediate: true,
    handler(value) { 
      document.getElementById(value).scrollIntoView();
    }
}

That should work in all cases.

Leave a comment