Skip to content

Instantly share code, notes, and snippets.

@oliviagardiner
Last active February 11, 2020 21:04
Show Gist options
  • Save oliviagardiner/625ee939a912d5afa66cc236c707d396 to your computer and use it in GitHub Desktop.
Save oliviagardiner/625ee939a912d5afa66cc236c707d396 to your computer and use it in GitHub Desktop.
Use Nuxt i18n + anchor oneline solution
// 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