smooth scroll for hash anchors

pull/1/head
Evan You 4 years ago
parent 444b362dea
commit ae4102bef7

@ -3,8 +3,9 @@ import { reactive, provide } from 'vue'
export const RouteSymbol = Symbol()
export function useRouter() {
const loc = location
const route = reactive({
path: location.pathname,
path: loc.pathname,
scrollPosition: window.scrollY
})
@ -16,16 +17,30 @@ export function useRouter() {
(e) => {
if (e.target.tagName === 'A') {
const { href, target } = e.target
const url = new URL(href)
if (
target !== `_blank` &&
href.startsWith(`${location.protocol}//${location.host}`)
url.protocol === loc.protocol &&
url.hostname === loc.hostname
) {
e.preventDefault()
// save scroll position before changing url
saveScrollPosition()
history.pushState(null, '', href)
route.path = location.pathname
route.scrollPosition = 0
if (url.pathname === loc.pathname) {
// smooth scroll bewteen hash anchors in the same page
if (url.hash !== loc.hash) {
e.preventDefault()
window.scrollTo({
left: 0,
top: e.target.offsetTop,
behavior: 'smooth'
})
}
} else {
e.preventDefault()
// save scroll position before changing url
saveScrollPosition()
history.pushState(null, '', href)
route.path = loc.pathname
route.scrollPosition = 0
}
}
}
},
@ -39,7 +54,7 @@ export function useRouter() {
*/
(e) => {
route.path = location.pathname
route.scrollPosition = e.state && e.state.scrollPosition || 0
route.scrollPosition = (e.state && e.state.scrollPosition) || 0
}
)

Loading…
Cancel
Save