Get Function value in javascript

Asked

Viewed 66 times

0

Code:

    window.onscroll = function (e) {
      console.log(this.oldScroll > this.scrollY)
      this.oldScroll = this.scrollY
    }

How do I turn this console.log in a Return and get the value false or true out of this Function?

note, I put this snippet inside a method that runs when the component is created, ie with the call in a created, it displays true or false on the console but nothing I tried has made me successful in using this information for another method or a var on

data: () => {}

of course, if there is a native function for this, and that is more cool, I accept the tip, the goal is to make two distinct toolbars go down or up when rolling the well

3 answers

2

The best way is to create a computed property:

computed: {
  newScrool () {
      return this.oldScroll > this.scrollY
  }
}

To use in another method is enough this.newScrool

On the page: {{newScrool}}

Read more in the official Vue documentation: Dados Computados

  • good, this I know how to do, however, as the information can go outside the scope window.onscroll = Function (and) { /get out of here/ }

  • @flourigh by which I understood the best way is for you to have a computed variable. Arrow in the life cycle the variables oldScroll e this.scrollY and adds the code of my reply.

  • I understand, so there is no way to get the information inside the scope?

0

Since you’re creating one Listener for the action scroll of the window you can store this information in some variable in data.

let vue = new Vue({
  el: "#app",
  data() {
    return {
      oldScroll: 0,
      scrollUP: false
    }
  },
  methods: {
    handleScroll(e) {
      if (this.oldScroll > window.scrollY) {
        this.scrollUP = true
      } else {
        this.scrollUP = false
      }
      this.oldScroll = window.scrollY
    }
  },
  created() {
    window.addEventListener('scroll', this.handleScroll);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" style="height:900px; padding-top:200px">
  Rolando para cima? {{scrollUP}}
</div>

  • really, I agree I could do this type, the problem is that I will have to do more variables on the date, this example I showed does not ask me to create other vars, there is no way to remove a Return from inside?

  • There is no return as it is an Event Listener. https://stackoverflow.com/questions/33501696/how-to-return-value-from-addeventlistener

  • understood, as it is an Event Listener your Return does not exist, thank you

-1

you could do something like that:

data: () => ({ scroll: 0 }),
created() {
      this.scroll = this.oldScroll > this.scrollY
      // ou this.store.dispatch ...
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.