简单的 Javascript 模块 - 本地存储模块

2025-05-27

简单的 Javascript 模块 - 本地存储模块

作为一名 Web 开发者,我的工作是在客户端处理来自服务器的大量连续数据。虽然不将数据存储在客户端是一个好习惯,但很多情况下,我们还是希望将一些信息存储在客户端以便更快地访问。一个很好的用例是应用主题theme: "light"theme: "dark"……

这就是我们可以使用浏览器本地存储的地方window.localStorage API。它是一个免费的存储空间,几乎所有主流浏览器都支持,我们可以保存大量安全的数据,以便在应用程序中快速使用。几乎所有主流浏览器都支持本地存储。您可以在浏览器的“应用程序”选项卡下,选择“本地存储”,然后点击您的域名,查看、修改或删除本地存储数据。

本地存储描述

正如您在下面的代码中看到的,我添加了所有我们最常使用本地存储的功能。通常,所有这些功能都单独编写在一个实用程序模块中。但在这里,我将其单独保留,以便无论发生什么变化,我们只需替换模块中的函数,而应用程序代码保持不变。The whole point of writing these functions together as a module is to keep the code clean, crisp and understandable.

// A localStorage object for performing crud operations on window.localStorage with ease

const Storage = {
  // check if local storage is supported on browser
  exists: (window.localStorage !== undefined),
  // get the local storage data of the key
  get(key) {
    if (!this.exists) return;
    const data = window.localStorage.getItem(key);
    if (!data) return;
    return JSON.parse(data);
  },
  // add a new data to given key in local storage
  add(key, data) {
    if (!this.exists) return;
    window.localStorage.setItem(key, JSON.stringify(data));
  },
  // remove the data by the given key from local storage
  remove(key) {
    if (!this.exists) return;
    window.localStorage.removeItem(key);
  },
  // wipe entire local storage of current domain
  wipe() {
    if (!this.exists) return;
    window.localStorage.clear();
  }
}

export default Storage;
Enter fullscreen mode Exit fullscreen mode

我在这里的模块上总共写了 5 个属性,它们将使用window.localStorage API和,如下所示。

1 exists.——这包含一个布尔值,用于检查当前浏览器是否支持本地存储。

2. get(key)- 此函数用于获取与参数中发送的键关联的数据。例如,它将get("name")获取本地存储中名为 key 的数据。此函数调用名为 window 的函数,localStorage.getItem()该函数接受一个参数“key”。

3. add(key, data)- 此函数用于将新数据添加到本地存储。key属性指定数据应添加到哪个键,data属性包含要添加的数据。此函数调用 window 函数,localStorage.setItem()该函数接受两个参数“key”和“data”。参数可以是任何值,例如字符串、数字、数组、对象等。

例如运行这个=>

Storage.add("myKey", { name: "Sooraj" })
Enter fullscreen mode Exit fullscreen mode

将其添加到名为“myKey”的键下
添加了本地存储

4. remove(key)- 此函数用于删除与参数中发送的键关联的数据。此函数调用名为“key”的窗口函数,localStorage.removeItem()该函数接受一个参数“key”。如果remove("myKey")调用该函数,之前添加的数据将从存储中清除。

5. wipe()- 我不会经常使用这个方法。此函数调用一个localStorage.clear()不带参数的窗口函数。此函数会清除该域中与客户端关联的所有本地存储数据。

好了,这就是我的存储模块。希望大家觉得它有用。快来试试吧……

文章来源:https://dev.to/soorajsnblaze333/simple-javascript-modules-local-storage-module-567p
PREV
具有主动模型模块的更智能的轨道服务
NEXT
使用 Vue 3 你可能不需要 Vuex