Vue-router中的scrollBehavior滚动属性不支持二级路由?怎么配置才能起作用呢?

scrollBehavior (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

我的目的是切换路由后每次都滚动到页面顶部
但是这样配置好像只对一级路由生效,像/page/1 -> /page/2 这样二级路由的切换就不起作用了。。应该怎么处理呢

阅读 1.7k
评论
    1 个回答

    支持二级路由啊,我的代码是这样写的。
    router/index.js

    const scrollBehavior = (to, from, savedPosition) => {
        if (savedPosition) {
            // savedPosition is only available for popstate navigations.
            return savedPosition;
        } else {
            const position = {}
                // new navigation.
                // scroll to anchor by returning the selector
            if (to.hash) {
                position.selector = to.hash
            }
            // check if any matched route config has meta that requires scrolling to top
            if (to.matched.some(m => m.meta.scrollToTop)) {
                // cords will be used if no selector is provided,
                // or if the selector didn't match any element.
                position.x = 0
                position.y = 0
            }
            // if the returned position is falsy or an empty object,
            // will retain current scroll position.
            return position;
        }
    };
    
    let router = new Router({
        mode: 'history',
        scrollBehavior,
        routes: [
            {
                path: '/detail/:id',
                name: 'Detail',
                component: Detail,
                meta: {
                    scrollToTop: true
                }
            }
        ]
    });
      撰写回答

      登录后参与交流、获取后续更新提醒

      相似问题
      推荐文章