Reputation: 41
I have page with a lot of components and I like to scroll to the point during opening the page.
In mounted
I have method which is pushing hash to the routes.
the page:
<template>
<section>
<ComponentA />
<ComponentB />
<ComponentC />
<div id="#scrollHere">
<ComponentD />
</div>
<ComponentE />
<ComponentF />
</section>
</template>
<script>
...
mounted() {
this.$router.push({name: 'pageName', hash: '#scrollHere'});
}
</script>
router.js
const router = new VueRouter({
routes,
mode: "history",
scrollBehavior(to) {
if (to.hash) {
return {
selector: to.hash
};
}
}
});
During opening the page nothing happen. Do you have any advices?
EDIT
I resolved the issue.
1. As said @Delena Malan (thanks!), removal #
from div id="#scrollHere"
was necessary.
2. I set Promise with timeOut in scrollBehaviour. The problem was in scrollBehavior my div didn't exist, so it was imposibble to scroll.
router.js
const scrollBehavior = to => {
if (to.hash) {
return new Promise(resolve => {
setTimeout(() => {
resolve({ selector: to.hash });
}, 1000);
});
}
};
Upvotes: 0
Views: 4552
Reputation: 2240
The only thing that you need in order to scroll top after each route change is to add this in router file
scrollBehavior(to, from, savedPosition){
return{ left: 0, top: 0}
}
in case you want to go back and visit your last browser position you can do this:
scrollBehavior(to, from, savedPosition){
if(savedPosition){
return savedPosition
}
return{ left: 0, top: 0}
}
Upvotes: 1