点击返回顶部代码vue
时间: 2023-12-24 07:48:08 浏览: 30
以下是一个简单的 Vue 组件,实现点击按钮返回页面顶部的功能:
```vue
<template>
<div>
<!-- 页面内容 -->
<div v-for="i in 100" :key="i" style="height: 50px; margin-bottom: 10px">{{ i }}</div>
<!-- 返回顶部按钮 -->
<button class="back-to-top" @click="scrollToTop">
返回顶部
</button>
</div>
</template>
<script>
export default {
methods: {
scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth",
});
},
},
};
</script>
<style>
.back-to-top {
position: fixed;
right: 20px;
bottom: 20px;
font-size: 16px;
padding: 10px;
border: none;
border-radius: 4px;
background-color: #007bff;
color: #fff;
cursor: pointer;
}
</style>
```
该组件中包含一个返回顶部按钮,点击该按钮会触发 `scrollToTop` 方法,使页面滚动到顶部。`scrollToTop` 方法中使用了 `window.scrollTo` 方法实现平滑滚动效果。样式中设置了按钮的基本样式和位置。