DEV Community

Meyti
Meyti

Posted on • Edited on

3 2

Controll Android Back Button in nativescript-vue

Just create a simple component:

import { android, AndroidApplication } from 'tns-core-modules/application'
import { isAndroid } from 'tns-core-modules/platform'

// WARNING: Just works on android
export default {
  props: {
    prevent: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      hooked: false
    }
  },
  watch: {
    prevent (newVal, oldVal) {
      if (newVal === oldVal) { return }
      if (newVal) {
        this.setHook()
      } else {
        this.clearHook()
      }
    }
  },
  render () {},
  mounted () {
    if (this.prevent) { this.setHook() }
  },
  beforeDestroy () {
    this.clearHook()
  },
  methods: {
    onBackEvent (data) {
      this.$emit('tap', data)
      if (this.prevent) {
        data.cancel = true // prevents default back button behavior
      }
    },
    setHook () {
      if (!isAndroid || this.hooked) { return }
      android.on(AndroidApplication.activityBackPressedEvent, this.onBackEvent)
      this.hooked = true
    },
    clearHook () {
      if (!isAndroid || !this.hooked) { return }
      android.off(AndroidApplication.activityBackPressedEvent, this.onBackEvent)
    }
  }
}

And use it like:

...
<android-back-button :prevent="true" @tap="onBackButton" />
...

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (5)

Collapse
 
taliastorymaker profile image
Talia

Thanks so much for this. Resources for Nativescript-Vue are pretty sparse, so you're a real life saver.

Collapse
 
ralphtolipas profile image
Silexet Winter

Nice! Any idea how to implement this in iOS?

Collapse
 
meyt profile image
Meyti

Sorry, I've no idea about iOS.

Collapse
 
kevuno profile image
Kevin Bastian

It worked for me but it disables the back button in all vue pages! What can I do to fix this?

Collapse
 
meyt profile image
Meyti

Well, there was a bug in my code, and fixed now. i've forgotten to check prevent property. thank you.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay