I can set scrolling behaviour to Vue.js Router like this:
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'index',
component: Main
},
{
path: '/some-path',
name: 'some-path',
component: SomePath
}
],
scrollBehavior() {
return {x: 0, y: 0}
}
})
This works perfectly when you click on the link with some page which is not current. When I click on the link which is already rendered, i.e. in the footer, nothing happens. Vue Router assumes there is no state transition. What is the preferred way to scroll up in this case?
As defined in the HTML specification, you can use href="#top" or href="#" to link to the top of the current page.
Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.
Sometimes, you might want to attach arbitrary information to routes like transition names, who can access the route, etc. This can be achieved through the meta property which accepts an object of properties and can be accessed on the route location and navigation guards.
You can't do this through vue-router
, but you can add a scroll-to-top method to every router-link
.
Just create a method like this:
methods: {
scrollToTop() {
window.scrollTo(0,0);
}
}
Add it to the link:
<router-link @click.native="$scrollToTop">
If you want to use it outside of your footer too, it's better to add it to the Vue prototype
Vue.prototype.$scrollToTop = () => window.scrollTo(0,0)
It's not a 100% solution but it's the simplest one
I couldn't get any of the above solutions working, and it was really frustrating.
What ended up working for me was the below:
const router = new Router({
mode: 'history',
routes: [...],
scrollBehavior() {
document.getElementById('app').scrollIntoView({ behavior: 'smooth' });
}
})
I mount my VueJs app to #app
so I can be certain it is present and is available for selection.
You could make use of behavior: smooth
:
moveTo () {
let to = this.moveToDown
? this.$refs.description.offsetTop - 60
: 0
window.scroll({
top: to,
left: 0,
behavior: 'smooth'
})
this.moveToDown = !this.moveToDown
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With