滚动到刷新或手动 URL 更改时锚定

Scroll to anchor on refresh or on manual URL change

我实现了 this post 中的代码,在使用路由器导航时启用滚动锚定。

但我注意到在刷新或手动导航(通过操纵 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 prop returns 正确的散列,但是 this.$scrollTo() 说找不到具有该 ID 的任何对象。

我只是用了一个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");