Hello everyone, I am the blogger of csdn: lqj_ myself
This is my personal blog homepage:
The latest uniapp graduation design column is also placed below:
https://blog.csdn.net/lbcyllqj/category_12346639.html?spm=1001.2014.3001.5482
Usually, I will also explain some things that you usually use in the Bilibili video,
Welcome to Bilibili:
Lu Miaoer's personal space-Lu Miaoer's personal homepage-哔哩哔哩Video
scroll behavior
We can vue-router
customize how the page scrolls when the route is switched. For example, when jumping to a new route, the page scrolls to a certain position; when switching routes, the page returns to the previous scroll position.
When creating a routing instance, we only need to provide a scrollBehavior
method:
const router = createRouter({
history: createWebHashHistory(),
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滚动到哪个的位置
}
})
scrollBehavior
Functions receive to
and from
route objects. The third parameter , is only available savedPosition
if this is a navigation (hitting the browser's back/forward buttons, or calling the method).popstate
router.go()
Scroll to a fixed distance
The function can return a ScrollToOptions
location object:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
// 始终滚动到顶部
return { top: 0 }
},
})
Scroll to element position
It is also possible to el
pass a CSS selector or a DOM element via . In this case, top
and left
will be treated as relative offsets to the element.
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
// 始终在元素 #main 上方滚动 10px
return {
// 也可以这么写
// el: document.getElementById('main'),
el: '#main',
top: -10,
}
},
})
Scroll to anchor position
It is also possible to simulate "scroll to anchor":
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
el: to.hash,
}
}
},
})
scroll to previous position
Back savedPosition
, when the browser 后退/前进
button is pressed, or router.go()
the method is called, the page will return to the previous scroll position:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
},
})
Tip: If a falsy value is returned, or an empty object, no scrolling will occur. We can also add to the returned object behavior: 'smooth'
to make scrolling more silky.
delayed scrolling
Sometimes, we don't want to perform scrolling behavior immediately. For example, when the page has a transition animation, we want to perform scrolling after the transition is over. To do this, we can return a Promise:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ left: 0, top: 0 })
}, 500)
})
}
})