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
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.
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'); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With