我在做项目的时候,有一个需求,在离开(跳转或者关闭)购物车页面或者刷新购物车页面的时候向服务器提交一次购物车商品数量的变化。
将提交的一步操作放到beforeDestroy钩子函数中。
beforeDestroy () {console.log(“销毁组件的) this.finalCart ()},
但是发现,beforeDestroy只能监听到页面间的跳转,无法监听到页面刷新和关闭标签页。
所以还是要借助,onbeforeunload事件。
顺便复习了一下JavaScript中的一些加载,卸载事件:
-
<李>页面加载时只执行,onload事件。李>
<李>页面关闭时,先,onbeforeunload事件,再,onunload事件。李>
<李>页面刷新时先执行,onbeforeunload事件,然后,onunload 事件,最后,onload 李事件。>
<李> 李>
1。在方法中定义事件方法:
方法:{ beforeunloadFn (e) { console.log(“刷新或关闭”)//? } }
2。在创建或安装者生命周期钩子中绑定事件
创建(){ 窗口。addEventListener (beforeunload, e=比;this.beforeunloadFn (e)) }
3。在摧毁钩子卸载事件
摧毁了(){ 窗口。removeEventListener (beforeunload, e=比;this.beforeunloadFn (e)) }
测试了页面刷洗和关闭都能监听到。
回到我自己的项目,可以使用,onbeforeunload事件和,beforeDestroy钩子函数结合:
创建(){ this.initCart () 窗口。addEventListener (beforeunload, this.updateHandler) }, beforeDestroy () { this.finalCart()//提交购物车的异步操作}, 摧毁了(){ 窗口。removeEventListener (beforeunload, this.updateHandler)}, 方法:{ updateHandler () { this.finalCart () }, finalCart () {//? } }
以上所述是小编给大家介绍的Vue监听页面刷新和关闭功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留的言,小编会及时回复大家的!