Last active
February 11, 2020 21:04
-
-
Save oliviagardiner/625ee939a912d5afa66cc236c707d396 to your computer and use it in GitHub Desktop.
Use Nuxt i18n + anchor oneline solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<div id="#anchor"></div> | |
<nuxt-link :to="{ path: localePath('pathname'), hash: '#anchor' }">Go to anchor</nuxt-link> | |
</div> | |
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// optional: alter the vue router scroll behavior to achieve smooth scrolling! | |
module.exports = { | |
// env, head, css, plugins, modules, rules etc. | |
router: { | |
scrollBehavior: async function(to, from, savedPosition) { | |
if (savedPosition) { | |
return savedPosition; | |
} | |
const findEl = async (hash, x = 0) => { | |
return ( | |
document.querySelector(hash) || | |
new Promise(resolve => { | |
if (x > 50) { | |
return resolve(document.querySelector("#content")); | |
} | |
setTimeout(() => { | |
resolve(findEl(hash, ++x || 1)); | |
}, 100); | |
}) | |
); | |
}; | |
if (to.hash) { | |
let el = await findEl(to.hash); | |
if ("scrollBehavior" in document.documentElement.style) { | |
return window.scrollTo({ top: el.offsetTop, behavior: "smooth" }); | |
} else { | |
return window.scrollTo(0, el.offsetTop); | |
} | |
} | |
return { x: 0, y: 0 }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment