在刷新时或手动更改URL时滚动到锚点。

问题描述 投票:0回答:1

我实施了来自 此职位在使用路由器导航时,可以实现滚动到锚。

但我注意到,在刷新或手动导航时(通过操作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的任何对象。

javascript vue.js vuejs2 anchor
1个回答
0
投票

我只是使用了一个 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");
© www.soinside.com 2019 - 2024. All rights reserved.