Controll Android Back Button in nativescript-vue

meyt

Meyti

Posted on March 15, 2020

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" />
...
💖 💪 🙅 🚩
meyt
Meyti

Posted on March 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related