Yur*_*vko 9 javascript vue.js vue-router
我正在尝试通过 VueJS 中的 scrollBehaviour 进行滚动以锚定。
通常,我使用以下方式更改当前路由器:
this.$router.push({path : 'componentName', name: 'componentName', hash: "#" + this.jumpToSearchField})
Run Code Online (Sandbox Code Playgroud)
我的 VueRouter 定义为:
const router = new VueRouter({
routes: routes,
base: '/base/',
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
let position = {}
if (to.hash) {
position = {
selector : to.hash
};
} else {
position = {x : 0 , y : 0}
}
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(position)
}, 10)
})
}
});
Run Code Online (Sandbox Code Playgroud)
我的路线:
[
{
path: '/settings/:settingsId',
component: Settings,
children: [
{
path: '',
name: 'general',
components: {
default: General,
summary: Summary
}
},
{
path: 'tab1',
name: 'tab1',
components: {
default: tab1,
summary: Summary
}
},
{
path: 'tab2',
name: 'tab2',
components: {
default: tab2,
summary: Summary
}
},
{
path: 'tab3',
name: 'tab3',
components: {
default: tab3,
summary: Summary
}
}
]
},
{
path: '/*',
component: Invalid
}
];
Run Code Online (Sandbox Code Playgroud)
假设我在tab1组件上,我想跳转到tab3组件上的锚定“测试”
在router.push() 之后, 我看到 scrollBehavior 被触发,组件从tab1切换到tab3以及 URL 被更改(例如http://localhost:8080/tab1到http://localhost:8080/tab3#test)但是windows 位置不放置在锚点的位置,而只是在窗口的顶部。
当然,我在 tab3 组件上有 id="test" 的 textarea
有什么问题?
小智 10
这在 Vue 3 中对我有用:
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, SavedPosition) {
if (to.hash) {
const el = window.location.href.split("#")[1];
if (el.length) {
document.getElementById(el).scrollIntoView({ behavior: "smooth" });
}
} else if (SavedPosition) {
return SavedPosition;
} else {
document.getElementById("app").scrollIntoView({ behavior: "smooth" });
}
},
});
Run Code Online (Sandbox Code Playgroud)
使用{left: 0, top: 0}而不是{x: 0, y: 0}它会起作用。
我认为这是 Vue 文档中的一个错误,因为如果您登录savedPosition控制台,您会看到{left: 0, top: 0},当您{x: 0, y: 0}像这样更改时,一切都会完美运行。
我无法获得围绕这项工作的任何其他解决方案,这真的令人沮丧。
最终为我工作的是以下内容:
const router = new Router({
mode: 'history',
routes: [...],
scrollBehavior() {
document.getElementById('app').scrollIntoView();
}
})
Run Code Online (Sandbox Code Playgroud)
我将我的 VueJs 应用程序安装到 #app,因此我可以确定它是否存在可供选择。
| 归档时间: |
|
| 查看次数: |
7797 次 |
| 最近记录: |