【问题标题】:Scroll to anchor on refresh or on manual URL change在刷新或手动 URL 更改时滚动到锚点
【发布时间】:2020-10-06 03:06:27
【问题描述】:

我实现了来自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 属性返回正确的哈希值,但 this.$scrollTo() 说它找不到任何具有该 ID 的对象。

【问题讨论】:

    标签: javascript vue.js vuejs2 anchor


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2020-08-22
      • 1970-01-01
      • 2021-03-20
      相关资源
      最近更新 更多