[英]How to scroll to the element using scrollBehavior and hash in Vue
I have page with a lot of components and I like to scroll to the point during opening the page.我有很多组件的页面,我喜欢在打开页面时滚动到该点。 In
mounted
I have method which is pushing hash to the routes.在
mounted
我有将哈希推送到路由的方法。 the page:这一页:
<template>
<section>
<ComponentA />
<ComponentB />
<ComponentC />
<div id="#scrollHere">
<ComponentD />
</div>
<ComponentE />
<ComponentF />
</section>
</template>
<script>
...
mounted() {
this.$router.push({name: 'pageName', hash: '#scrollHere'});
}
</script>
router.js路由器.js
const router = new VueRouter({
routes,
mode: "history",
scrollBehavior(to) {
if (to.hash) {
return {
selector: to.hash
};
}
}
});
During opening the page nothing happen.在打开页面期间什么也没有发生。 Do you have any advices?
你有什么建议吗?
EDIT I resolved the issue.编辑我解决了这个问题。 1. As said @Delena Malan (thanks!), removal
#
from div id="#scrollHere"
was necessary. 1. 正如@Delena Malan所说(谢谢!),从
div id="#scrollHere"
中删除#
是必要的。 2. I set Promise with timeOut in scrollBehaviour. 2. 我在 scrollBehaviour 中设置了 Promise 和 timeOut。 The problem was in scrollBehavior my div didn't exist, so it was imposibble to scroll.
问题出在 scrollBehavior 中,我的 div 不存在,因此无法滚动。
router.js路由器.js
const scrollBehavior = to => {
if (to.hash) {
return new Promise(resolve => {
setTimeout(() => {
resolve({ selector: to.hash });
}, 1000);
});
}
};
The only thing that you need in order to scroll top after each route change is to add this in router file为了在每次路由更改后滚动顶部,您唯一需要做的就是在路由器文件中添加它
scrollBehavior(to, from, savedPosition){
return{ left: 0, top: 0}
}
in case you want to go back and visit your last browser position you can do this:如果您想返回并访问上次浏览器位置,您可以执行以下操作:
scrollBehavior(to, from, savedPosition){
if(savedPosition){
return savedPosition
}
return{ left: 0, top: 0}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.