Home > Software engineering >  Vue 3: What's the proper way of handling event listeners like "visibilitychange" and
Vue 3: What's the proper way of handling event listeners like "visibilitychange" and

Time:01-22

Note A: I'm not talking about event listeners on elements, like @click

Note B: I've been looking "all over" for this but couldn't find it anywhere. Feel free to slap my face if the answer is out there.

Note C: I'm a beginner with Vue trying to learn stuff

I guess I could put those kind of event listeners within main.js, but that just seems a bit off? Also how would I call functions declared within App.vue from main.js?

I'm guessing there's a better and more proper way to handle this within App.vue and the life cycle?

Any help would be greatly appreciated!

Here are two vanilla JS code examples, one with window and one with document:

window.addEventListener('offline', function() {
  alert('You seem to be offline!');
});

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    alert('Hello again!');
  }
});

CodePudding user response:

You can set the event listener in the created or mounted hook in your SFC like this:

<script>
export default {
  created () {
    document.addEventListener('visibilitychange', this.handleVisibility, false)
  },
  methods: {
    handleVisibility (e) {
      if (document.visibilityState === 'hidden') {
        // do what you like
      } else {
        // again do as you like
      }
    }
  }
};
</script>
  •  Tags:  
  • Related