VueJS Browser back を検知する detect browser back

環境:

vue@2.6.14

vuex@3.6.2

 

@app.js

history.replaceState(null, '', null)
window.addEventListener('popstate', function() {
  vue.$store.commit('ROUTER_DETECT_BROWSER_GO_AND_BACK')
})

 

@router.js

const state = {

  detectBrowserGoAndBack: 0

}

const mutations = {

  'ROUTER_DETECT_BROWSER_GO_AND_BACK' (state) {

    state.detectBrowserGoAndBack++

  } 

}

 

@TargetComponent.vue

watch: {

  '$store.state.router.detectBrowserGoAndBack' () {

    // do something when browser go and back detected

  }

}

 

ref:

qiita.com