简体   繁体   English

在 vue.js 中使用计算的滚动顶部

[英]scrollTop using computed in vue.js

Here is part of my code这是我的代码的一部分

<template>
  <button v-show="visible" @click="backToTop">👆</button>
</template>

<script lang="ts">
export default {
  computed: {
    visible() {
      return document.documentElement.scrollTop != 0
    }
  }
}
</script>

The button doesn't disappear when i scroll the page to the top.当我将页面滚动到顶部时,该按钮不会消失。

try:尝试:

window.scrollY

this will detect scrolling your document and it's value changes based on the current scroll position这将检测滚动您的文档,它的值会根据当前滚动位置发生变化

for accessing the scroll height of your window, you need to access window instead of document要访问窗口的滚动高度,您需要访问窗口而不是文档

You need to listen to scroll event, try like following snippet:您需要收听滚动事件,请尝试以下代码段:

 const app = Vue.createApp({ data() { return { visible: false } }, methods: { handleScroll (event){ this.visible = window.scrollY != 0 ? true : false }, backToTop() { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }) } }, created () { window.addEventListener('scroll', this.handleScroll); }, destroyed () { window.removeEventListener('scroll', this.handleScroll); }, }) app.mount('#demo')
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> <p>x</p><p>x</p><p>x</p><p>x</p> <button v-show="visible" @click="backToTop">👆</button> <p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p><p>x</p> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM