Skip to content

Instantly share code, notes, and snippets.

@meyt
Last active June 11, 2022 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meyt/fbb0caa8b814aa87a4547dc478d8f65b to your computer and use it in GitHub Desktop.
Save meyt/fbb0caa8b814aa87a4547dc478d8f65b to your computer and use it in GitHub Desktop.
Navigation-back detector for vue@2 vue-router@3 http://codepen.io/barname_nevis/pen/jOZQwby
// basic usage
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueNavbackDetector from './vue-navback-detector.js'
const routes = []
const router = new VueRouter({ routes })
Vue.use(VueNavbackDetector, { router })
new Vue({ router }).$mount('#app')
// use as nuxt@2 plugin
import Vue from 'vue'
import VueNavbackDetector from './vue-navback-detector.js'
export default function (ctx, inject) {
Vue.use(VueNavbackDetector, { router: ctx.app.router })
}
export default {
install (Vue, options) {
const opts = { globalKey: '__VueRouterIsNavback', router: null, ...options }
function handlePop () { window[opts.globalKey] = true }
function handlePush () { window[opts.globalKey] = false }
// attach
window[opts.globalKey] = false
window.addEventListener('popstate', handlePop)
opts.router.afterEach(() => setTimeout(handlePush, 0))
// instance access
Object.defineProperty(Vue.prototype, '$isNavback', {
get () { return window[opts.globalKey] }
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment