首页 > 解决方案 > 在刷新或手动 URL 更改时滚动到锚点

问题描述

我实现了这篇文章中的代码,在使用路由器导航时启用滚动锚点。

但我注意到,在刷新或手动导航(通过操作 URL)时,页面不会按预期滚动到锚点。

我可以将此代码添加到所有页面,它会起作用:

mounted() {
    console.log('Location:', location.hash); //returns '#options'
    console.log('Route:', this.$route.hash); //returns '#options'

    if (location.hash)
        this.$nextTick().then(() => this.$scrollTo(location.hash, 700));
}

是否有任何全局方法来设置此代码,而不必在每个页面中设置代码?

我试图在App.vue文件上设置它,location.hash道具返回正确的哈希,但this.$scrollTo()说它找不到任何具有该 ID 的对象。

标签: javascriptvue.jsvuejs2anchor

解决方案


我只是使用了vue-router导航守卫:

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,

    scrollBehavior (to, from, savedPosition) {
        if (to.hash) {
            this.app.$scrollTo(to.hash, 700);
            return { selector: to.hash }
        } else if (savedPosition) {
            return savedPosition;
        } else {
            //When the route changes, the page should scroll back to the top.
            this.app.$scrollTo('#app', 700);
            return { x: 0, y: 0 }
        }
    }
});

router.afterEach((to, from) => {
    if (to.hash && to.path != from.path)
        Vue.nextTick().then(() => VueScrollTo.scrollTo(to.hash, 700));
});

与问题无关,但与带有哈希的导航有关:

如果您要在 中发布您的网站GitHub Pages,则需要添加接下来的两个部分。

添加一个 404.html 静态页面,将导航重定向回根页面,但在sessionStorage:

<script>
    const segment = 1;  
    //Gets the relative path and the hash of the URL.  
    sessionStorage.redirect = '/' + location.pathname.slice(1).split('/').slice(segment).join('/');  
    sessionStorage.hash = location.hash;  

    //Forces the navigation back to the main page, since it's the only entry point that works.
    location.replace(location.pathname.split('/').slice(0, 1 + segment).join('/'));
</script>

更改您的main.js页面以期望重定向参数:

new Vue({
    router,
    i18n,
    render: (h) => h(App),
    created() {
        //If a redirect exists, tell the router.
        if (sessionStorage.redirect) {
            const redirect = sessionStorage.redirect;
            const hash = sessionStorage.hash;
            delete sessionStorage.redirect;
            delete sessionStorage.hash;

            this.$router.push(redirect + hash);
        }
    }
}).$mount("#app");

推荐阅读