nuxt3之页面跳转scroll到指定anchor: 开始看了:https://stackoverflow.com/questions/73932280/nuxt-3-smooth-scrolling-with-hash-links
但是上面这个方法并没有生效
最后自己想到一个好的方法:
在 created 下定义
if (process.client) {
if (_.has(this.$route, 'hash') && this.$route.hash){
window.scrollTo({top: this.getTop(this.$route.hash)})
}
}
在 methods下定义如下获取指定anchor元素距离顶部的offSet值
getTop(hash){
const el = document.querySelector(hash)
return el.offsetTop
}
这样就可以解决,页面跳转到指定anchor的问题,其实在上面的链接里面,核心的也就是获取元素的offSet的值,单独拿出来看看:
import { defineNuxtPlugin } from "#app";
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.$router.options.scrollBehavior = async (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition;
}
const findEl = async (hash, x = 0) => {
return (
document.querySelector(hash) ||
new Promise((resolve) => {
if (x > 0) {
return resolve(document.querySelector("#app"));
}
setTimeout(() => {
resolve(findEl(hash, 1));
}, 300);
})
);
};
if (to.hash) {
const el = await findEl(to.hash);
if ("scrollBehavior" in document.documentElement.style) {
console.log("hash path hit scroll to");
return window.scrollTo({ top: el.offsetTop, behavior: "smooth" });
} else {
return window.scrollTo(0, el.offsetTop);
}
}
return { left: 0, top: 0, behaviour: "smooth" };
};
})
