猿问

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

scrollBehavior (to, from, savedPosition) {

  return { x: 0, y: 0 }

}

我的目的是切换路由后每次都滚动到页面顶部

但是这样配置好像只对一级路由生效,像/page/1 -> /page/2 这样二级路由的切换就不起作用了。。应该怎么处理呢


呼啦一阵风
浏览 684回答 1
1回答

泛舟湖上清波郎朗

支持二级路由啊,我的代码是这样写的。router/index.jsconst 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            }        }    ]});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答