vue3写一个返回顶部按钮
时间: 2023-10-19 15:05:39 浏览: 222
可以通过以下步骤来实现一个返回顶部按钮:
1. 在 Vue 组件中创建一个按钮,并为其添加一个点击事件:
```html
<template>
<div>
<button @click="scrollToTop">返回顶部</button>
</div>
</template>
```
2. 在 Vue 组件的 script 中定义 scrollToTop 方法,使用 window.scrollTo() 方法将页面滚动到顶部:
```js
<script>
export default {
methods: {
scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
}
}
};
</script>
```
3. 添加样式来使按钮看起来更好:
```css
button {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 20px;
border: none;
background-color: #4caf50;
color: white;
font-size: 16px;
cursor: pointer;
}
```
完整的代码示例:
```html
<template>
<div>
<button @click="scrollToTop">返回顶部</button>
</div>
</template>
<script>
export default {
methods: {
scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
}
}
};
</script>
<style>
button {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 20px;
border: none;
background-color: #4caf50;
color: white;
font-size: 16px;
cursor: pointer;
}
</style>
```
阅读全文
相关推荐


















