Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I handle back button within methods in vuejs 2?

Tags:

I need some help in vuejs 2. I want to detect back button pressed event. I did some research and found this,

document.addEventListener("backbutton", yourCallBackFunction, false"); 

I think it is global event. I need something local, within a method. where i can use some logic.

methods: {     backButtonPressed() {     } } 

Or can i bind the global one to local function? Can anyone help me with that? TIA

like image 456
Alauddin Ahmed Avatar asked Dec 26 '17 06:12

Alauddin Ahmed


2 Answers

Add the event on your mounted method on your root Vue component (the one the Vue instance is tied to.

var app = new Vue({   el: '#app',   data: {     message: 'Hello Vue!'   },   methods: {     yourCallBackFunction () {       // Your logic     }   }   mounted () {     document.addEventListener("backbutton", this.yourCallBackFunction, false);   },   beforeDestroy () {     document.removeEventListener("backbutton", this.yourCallBackFunction);   } }) 

We also remove it on beforeDestroy to keep things tidy.

Note: I've not personally used the back button event so have added it to this example only because you say it's working but need a way to globally handle it. This code will do just that.

Note: As per @Luke's comment - we add the listener in the mounted event so it doesn't execute for in the SSR context. If SSR isn't a factor / consideration then we can use the created lifecycle hook.

like image 121
webnoob Avatar answered Sep 20 '22 22:09

webnoob


If still someone come across this issue. A solution for an event listener for browser-back is https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onpopstate

window.onpopstate = function() {    alert('browser-back');  };
like image 27
Claudio Avatar answered Sep 24 '22 22:09

Claudio