I
I
Ibishka2020-02-18 22:11:57
JavaScript
Ibishka, 2020-02-18 22:11:57

Why doesn't the body scroll check work correctly?

<template>
  <div :class="{ 'full-height': checkRouteName }" id="app">
    <header class="header">
      <div class="container">
        <div class="header__row">
          <router-link to="/">
            <img src="@/assets/img/logo.svg" alt="Triangle" />
          </router-link>
          <nav class="menu">
            <li class="menu__item">
              <router-link to="/" class="menu__link" active-class="active" exact
                >Home</router-link
              >
            </li>
            <li class="menu__item">
              <router-link to="/news" class="menu__link" active-class="active"
                >News</router-link
              >
            </li>
            <li class="menu__item">
              <router-link to="/bands" class="menu__link" active-class="active"
                >Bands</router-link
              >
            </li>
            <li class="menu__item">
              <router-link to="/media" class="menu__link" active-class="active"
                >Media</router-link
              >
            </li>
          </nav>
          <button class="hamburger"></button>
        </div>
      </div>
    </header>
    <router-view />
    <button
      class="scroll"
      :class="{ visible: checkScroll }"
      id="scroll"
    ></button>
  </div>
</template>
<script>
export default {
  methods: {
    checkScroll() {
      return document.body.scrollTop > 0;
    }
  },
  computed: {
    checkRouteName() {
      return this.$route.name == "Home";
    }
  }
};
</script>

But alas, the button is always visible. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-19
@Ibishka

does not work correctly

The word "correct" is superfluous here. It doesn't fucking work at all.
You have the check in the method, and the methods - I know, it will sound very unexpected for you - they must be called. What don't you do. But, of course, adding parentheses will not help you much - the call will only occur during rendering, and it is not related to scrolling.
It will be correct like this: add a property that stores the current scroll; update it on the scroll event (you need to hang the appropriate handler on the scrollable element); assign classes or whatever you need depending on the value of this property:
data: () => ({
  scroll: 0,
}),
computed: {
  buttonClass() {
    return что-то, зависящее от значения this.scroll;
  },
},
created() {
  const { body } = document;
  const onScroll = () => this.scroll = body.scrollTop;
  body.addEventListener('scroll', onScroll);
  this.$on('hook:beforeDestroy', () => body.removeEventListener('scroll', onScroll));
},

<button :class="buttonClass"></button>
https://jsfiddle.net/kLwhbec5/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question