:::

14-7-4 將 localStorage 做成 plugin

  1. localStorage的用法:
    1. https://developer.mozilla.org/zh-TW/docs/Web/API/Window/localStorage
    2. https://medium.com/%E9%BA%A5%E5%85%8B%E7%9A%84%E5%8D%8A%E8%B7%AF%E5%87%BA%E5%AE%B6%E7%AD%86%E8%A8%98/javascript-localstorage-%E7%9A%84%E4%BD%BF%E7%94%A8-e0da6f402453
  2. 建立plugin/localStorage.js
    export default ({ app }, inject) => {
      inject("localStorage", {
        set(key = "", val = {}) {
          localStorage.setItem(key, JSON.stringify(val));
        },
        get(key = "") {
          const obj = JSON.parse(localStorage.getItem(key));
          // 避免傳回 null
          if (!obj) {
            return {};
          }
          return obj;
        },
        remove(key = "") {
          localStorage.removeItem(key);
        },
        removeAll() {
          localStorage.clear();
        }
      });
    };
    

     

  3. 加入nuxt.config.js設定
      plugins: [
        "~/plugins/hello.js",
        "~/plugins/axios.js",
        "~/plugins/notification.js",
        "~/plugins/localStorage.js"
      ],

     

  4. 如此,便可方便的localStorage使用
      mounted() {
        this.$hello("我在前端被mounted了");
        this.$localStorage.set("userData", { name: "tad", age: 48 });
        console.log('userData', this.$localStorage.get("userData"));
      },

     


:::

書籍目錄

展開 | 闔起

快速登入


http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1883%26tbsn%3D33

計數器

今天: 1018101810181018
昨天: 3068306830683068
總計: 8077523807752380775238077523807752380775238077523