vue项目中beforeDestroy或destroyed使用this.$notify.closeAll()失效
需求是进入系统,在首页右下角弹出提示框,使用到element的this.$notify功能,但是发现存在几个问题,
第一个是this.$notify优先级太高,如果设置了不主动关闭,即使跳转到其它页面也不会关闭;
第二个是由于created时需要调接口查看是否需要展示notify,实际发现只要页面刷新一次就会出现一个notify,上一个不会关闭;
第三个是发现使用this.$notify.close()关闭不了notify。
解决方法:
第二个问题好解决,只要在调完接口,发现需要展示notify时,先关闭原先的notify再执行新的this. n o t i f y 即可:在 t h i s . notify即可:在this. notify即可:在this.notify前面先使用this.$notify.close();
但是this. n o t i f y . c l o s e ( ) 不生效啊,原来是因为 t h i s . notify.close()不生效啊,原来是因为this. notify.close()不生效啊,原来是因为this.notify.close()方法用于关闭单个通知,它需要传入一个参数,即要关闭的通知的id。这里我没有id,所以解决第三个问题,将this. n o t i f y . c l o s e ( ) 改为 t h i s . notify.close()改为this. notify.close()改为this.notify.closeAll()就有效果了;
然后是第一个问题,希望离开首页的时候,notify关掉,本来是准备在beforeDestroy或者destroyed里面写this. n o t i f y . c l o s e A l l ( ) ;打印发现离开页面根本没调用 b e f o r e D e s t r o y 或者 d e s t r o y e d ;研究页面发现原来是页面使用了 k e e p − a l i v e ;被 k e e p − a l i v e 包裹的组件会缓存组件实例,而不是销毁他们,但是这个页面又必须使用 k e e p − a l i v e ,那我们只能去看生命周期里的其他方法,于是就找到了 a c t i v a t e d , d e a c t i v a t e d ;离开组件时会执行 d e a c t i v a t e d ;所以我们在 d e a c t i v a t e d 里写 t h i s . notify.closeAll();打印发现离开页面根本没调用beforeDestroy或者destroyed;研究页面发现原来是页面使用了keep-alive;被keep-alive包裹的组件会缓存组件实例,而不是销毁他们,但是这个页面又必须使用keep-alive,那我们只能去看生命周期里的其他方法,于是就找到了activated,deactivated;离开组件时会执行deactivated;所以我们在deactivated里写this. notify.closeAll();打印发现离开页面根本没调用beforeDestroy或者destroyed;研究页面发现原来是页面使用了keep−alive;被keep−alive包裹的组件会缓存组件实例,而不是销毁他们,但是这个页面又必须使用keep−alive,那我们只能去看生命周期里的其他方法,于是就找到了activated,deactivated;离开组件时会执行deactivated;所以我们在deactivated里写this.notify.closeAll()就好了。
全部代码:
created() {this.warningCheck()},deactivated() {this.$notify.closeAll()},methods: {async warningCheck() {const res = await this.$api.接口名()if (res) {this.$notify.closeAll()this.$notify({title: '库存预警',position: 'bottom-right',duration: 0,dangerouslyUseHTMLString: true,message: `<p>当前库存低于预警数量,请及时处理</p><div style="display:flex;justify-content: flex-end;"><div style="width:40px;text-align:center;background:#7297e7;color:#ffffff;border-radius:4px;">处理</div></div>`,onClick: function () {this.$notify.closeAll()this.$module.push({name: 'stockWarning' // 要去的菜单})}})}}}