本文介绍了如何模拟“滚动到锚点"在 Vue Router 中加载页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下路由器配置的小型 Vue.js SPA,取自 文档:

export default new VueRouter({路线,//上面定义...模式:'历史',滚动行为(到,从,保存位置){如果(to.hash){返回 { 选择器:to.hash }} else if (savedPosition) {返回保存位置;} 别的 {返回 { x: 0, y: 0 }}}})

考虑主页上的链接:

它按预期跳转到锚元素

...

.但是,当您激活链接,然后从 #services 滚动离开并刷新页面时,您将不会回到#services.即使 URL 中仍包含哈希值(例如,以 app.dev/#services 的形式),您仍将停留在上次中断的位置.

如果 URL 包含其哈希值(并且,该哈希值对应于有效的现有元素),我该如何配置路由器,以便在页面加载时将用户带到锚元素?

解决方案

我遇到了同样的问题,但也希望有一个动画滚动到哈希.我能够使用 vue-scrollto 检查这两个功能.https://github.com/rigor789/vue-scrollto

这样的事情应该可以工作.

//导入从 'vue-scrollto' 导入 VueScrollTo;//...滚动行为(到,从,保存位置){如果(to.hash){VueScrollTo.scrollTo(to.hash, 700);返回 { 选择器:to.hash }} else if (savedPosition) {返回保存位置;} 别的 {返回 { x: 0, y: 0 }}}

那样,它总是为散列设置动画.如果您不想设置动画,请使用 0 而不是 700 作为时间.如果您不喜欢使用该模块,您可以使用 这里

I have a small Vue.js SPA with the following router configuration, taken from the docs:

export default new VueRouter({
    routes, // defined above...

    mode: 'history',

    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return { selector: to.hash }
        } else if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 }
        }
    }
})

Consider a link on the homepage:

<router-link to="#services">Services</router-link>

It jumps to the anchor element <div id="services">...</div> as expected. However, when you activate the link, then scroll away from #services, and refresh the page, you will not be brought back to #services. You will stay in the same position where you left off, even though the URL would still have the hash in it (e.g. in the form of app.dev/#services).

How can I configure the router so that on page load, it bring the user to the anchor element, given that the URL contains its hash (and, well, that hash corresponds to a valid existing element)?

解决方案

I had the same problem but also wanted to have an animated scroll to the hash. I was able to check off both features with vue-scrollto.https://github.com/rigor789/vue-scrollto

Something like this should work.

// import
import VueScrollTo from 'vue-scrollto';

//...

scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
        VueScrollTo.scrollTo(to.hash, 700);
        return { selector: to.hash }
    } else if (savedPosition) {
        return savedPosition;
    } else {
        return { x: 0, y: 0 }
    }
}

That way, it always animates to the hash.If you don't want to animate, use 0 as the time instead of 700.If you don't like using that module, you can manually jump to the anchor via regular javascript using the techniques described here

这篇关于如何模拟“滚动到锚点"在 Vue Router 中加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:07