【问题标题】:How to clean localeStorage only after closing the browser (VueJs)?如何仅在关闭浏览器(VueJs)后清理 localeStorage?
【发布时间】:2020-09-15 06:53:50
【问题描述】:

问题是:“如何仅在关闭浏览器(而不是关闭浏览器选项卡并重新加载页面)后清理 localeStorage。这必须在 Vue 组件中实现。 找到以下解决方案(Clear localStorage on tab/browser close but not on refresh):

window.onbeforeunload = function (e) {
    window.onunload = function () {
            window.localStorage.isMySessionActive = "false";
    }
    return undefined;
};

window.onload = function () {
            window.localStorage.isMySessionActive = "true";
};

但我不明白如何正确以及在哪里调用这些侦听器。

【问题讨论】:

    标签: vue.js events vuejs2 vue-component


    【解决方案1】:

    您可以在main.js 文件或App.vue 文件中简单地注册您的听众

    main.js

    import Vue from "vue";
    import App from "./App.vue";
    
    Vue.config.productionTip = false;
    
    new Vue({
      beforeMount() {
        window.addEventListener("load", this.onLoad);
        window.addEventListener("beforeunload", this.onUnload);
      },
      beforeDestroy() {
        window.removeEventListener("load", this.onLoad);
        window.removeEventListener("beforeunload", this.onUnload);
      },
      methods: {
        onLoad(event) {
          window.localStorage.setItem("isMySessionActive", true);
        },
        onUnload(event) {
          window.localStorage.setItem("isMySessionActive", false);
        }
      },
      render: (h) => h(App)
    }).$mount("#app");
    

    App.vue

    <template>
      <div id="app">
        <img alt="Vue logo" src="./assets/logo.png" width="25%">
        <HelloWorld msg="Hello World!"/>
      </div>
    </template>
    
    <script>
    import HelloWorld from "./components/HelloWorld";
    
    export default {
      name: "App",
      components: {
        HelloWorld
      },
      beforeMount() {
        window.addEventListener("load", this.onLoad);
        window.addEventListener("beforeunload", this.onUnload);
      },
      beforeDestroy() {
        window.removeEventListener("load", this.onLoad);
        window.removeEventListener("beforeunload", this.onUnload);
      },
      methods: {
        onLoad(event) {
          window.localStorage.setItem("isMySessionActive", true);
        },
        onUnload(event) {
          window.localStorage.setItem("isMySessionActive", false);
        }
      }
    };
    </script>
    
    <style>
    #app {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
    

    【讨论】:

    • 感谢您的回答,无论是否有效,我都会尽快添加)
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多