所以我想防止我的 Vue App 在 Vuex 状态中有某个值时关闭浏览器窗口。我认为我遇到的问题是 Vuex 存储在生命周期 Hook 中不可用。
这是我正在尝试的:
mounted: function () {
window.addEventListener('beforeunload', function (event) {
console.log('unload');
if (this.$store.state.curOrder != ''){
event.preventDefault()
event.returnValue = ""
}
}, false)
},
当我尝试关闭浏览器窗口时,控制台日志是正确的,但随后出现此错误:
Uncaught TypeError: Cannot read property 'state' of undefined
有什么解决方法可以让我在关闭浏览器之前访问 Vuex?
最佳答案
可能是范围问题,这样试试。
创建一个单独的方法。
methods: {
onClose(event) {
console.log('unload');
if (this.$store.state.curOrder != ''){
event.preventDefault()
event.returnValue = ""
}
}
}
对于您的听众,更改为:
window.addEventListener('beforeunload', this.onClose);
关于javascript - 看。根据 vuex 状态防止窗口关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59457165/