欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何利用VUE監(jiān)聽(tīng)網(wǎng)頁(yè)關(guān)閉并執(zhí)行退出操作

 更新時(shí)間:2023年08月14日 10:34:55   作者:Gua_guagua  
這篇文章主要給大家介紹了關(guān)于如何利用VUE監(jiān)聽(tīng)網(wǎng)頁(yè)關(guān)閉并執(zhí)行退出操作的相關(guān)資料,因?yàn)轫?xiàng)目中需求,瀏覽器關(guān)閉時(shí)進(jìn)行一些操作處理,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下

最近在項(xiàng)目中遇到了一個(gè)需求,需要監(jiān)聽(tīng)頁(yè)面關(guān)閉,在頁(yè)面關(guān)閉時(shí)彈出提示框,并在離開(kāi)頁(yè)面時(shí)觸發(fā)退出操作。因?yàn)槭怯肰UE進(jìn)行開(kāi)發(fā)的,所以先在mounted()中創(chuàng)建頁(yè)面關(guān)閉的監(jiān)聽(tīng)

window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
window.addEventListener("unload", (e) => this.unloadHandler(e));

第一個(gè)監(jiān)聽(tīng)的是頁(yè)面關(guān)閉之前,對(duì)應(yīng)的方法可以寫(xiě)做

// 頁(yè)面關(guān)閉之前,觸發(fā)提示框
    beforeunloadHandler(e) {
      if (e) {
        e = e || window.event;
        console.log(e);
        if (e) {
          e.returnValue = "關(guān)閉提示";
        }
        return "關(guān)閉提示";
      }
    },

第二個(gè)監(jiān)聽(tīng)的是頁(yè)面關(guān)閉的時(shí)候,這里面可以調(diào)用退出登錄的方法,但是記得要用同步調(diào)用的方法,axios默認(rèn)的是異步調(diào)用的方法

// 頁(yè)面關(guān)閉
    async unloadHandler(e) {
      // 退出登錄
      await this.handleGoLog();
    },

最后記得在destroyed()中,注銷監(jiān)聽(tīng)

destroyed() {
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    window.removeEventListener("unload", (e) => this.unloadHandler(e));
  },

補(bǔ)充知識(shí):vue實(shí)現(xiàn)關(guān)閉瀏覽器退出登錄功能(區(qū)別關(guān)閉和刷新)

項(xiàng)目場(chǎng)景:

在實(shí)現(xiàn)單點(diǎn)登錄時(shí),發(fā)現(xiàn)關(guān)閉瀏覽器后,并不會(huì)自動(dòng)退出登錄

解決方案:在app.vue中書(shū)寫(xiě)如下代碼

? data() {
? ? return {
? ? ? gap_time: 0,
? ? ? beforeUnload_time: 0,
? ? };
? },
? methods: {
? ? // 關(guān)閉窗口之前執(zhí)行
? ? beforeunloadHandler() {
? ? ? this.beforeUnload_time = new Date().getTime();
? ? },
? ? unloadHandler() {
? ? ? this.gap_time = new Date().getTime() - this.beforeUnload_time;
? ? ? //判斷是窗口關(guān)閉還是刷新 毫秒數(shù)判斷 網(wǎng)上大部分寫(xiě)的是5
? ? ? if (this.gap_time <= 10) {
? ? ? ? logOut() // 退出登錄接口 這里應(yīng)當(dāng)換為個(gè)人的登出方法
? ? ? } else {
? ? ? }
? ? },
? },
? destroyed() {
? ? // 移除監(jiān)聽(tīng)
? ? window.removeEventListener("beforeunload", () => this.beforeunloadHandler());
? ? window.removeEventListener("unload", () => this.unloadHandler());
? },
? mounted() {
? ? // 監(jiān)聽(tīng)瀏覽器關(guān)閉
? ? window.addEventListener("beforeunload", () => this.beforeunloadHandler());
? ? window.addEventListener("unload", () => this.unloadHandler());
? }

然后,再關(guān)閉瀏覽器后,就會(huì)自動(dòng)調(diào)用我們的退出登錄函數(shù)了。 

總結(jié) 

到此這篇關(guān)于如何利用VUE監(jiān)聽(tīng)網(wǎng)頁(yè)關(guān)閉并執(zhí)行退出操作的文章就介紹到這了,更多相關(guān)VUE監(jiān)聽(tīng)網(wǎng)頁(yè)關(guān)閉并退出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論