vue项目回到顶部的两种超简单实现方法
作者:喵喵酱仔__
这篇文章主要给大家介绍了关于vue项目回到顶部的两种超简单实现方法,页面切换回到顶部是一个很常见的功能,文中通过代码介绍的非常详细,需要的朋友可以参考下
vue 中实现回到顶部的两种方式:
(1)锚点方式
通过点击锚点回到指定位置:
<template> <div id="topAnchor" ref="faultTree" class="wrap"> <a id="TOPUp" href="#topAnchor" rel="external nofollow" > <img style="width: 100%;height: 100%;" src="../../../../assets/top.png" alt=""> </a> <!--其他业务逻辑代码--> ... </div> </template>
样式:
<style>
#TOPUp{
position: fixed;
right: 45px;
bottom: 100px;
width: 40px;
height: 40px;
z-index: 99999999;
box-shadow: 0px 0px 4px 4px #ecefef;
border-radius: 600px;
}
</style>(2)scrollTop
通过点击事件将scrollTop重置为0,从而达到返回顶部的效果。
<template>
<div class="hello_world">
<button class="top" @click="toTop">^</button>
</div>
</template>
<script>
export default {
methods: {
toTop() {
document.documentElement.scrollTop = 0;
},
},
};
</script>
<style>
.hello_world {
height: 5000px;
}
.top {
position: fixed;
width: 30px;
height: 30px;
bottom: 50px;
right: 100px;
background-color: aqua;
}
</style>代码地址:https://gitcode.net/sinat_33255495/vue
附:vue实现刷新页面,页面回到顶部
使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。
- vue-router中有一个滚动行为-scrollBehavior ,
const router = createRouter({
history: createWebHashHistory(),
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滚动到哪个的位置
// vue2.0 x y 控制
// vue3.0 left top 控制
return { left: 0, top: 0 } }
})- 加全局守卫
在main.js中加
router.afterEach((to,from,next)=>{
window.scrollTo(0,0);
})总结
到此这篇关于vue项目回到顶部的两种超简单实现方法的文章就介绍到这了,更多相关vue项目回到顶部内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
