版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useIDBKeyval.cjs 2.0 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var shared = require('@vueuse/shared');
  3. var vueDemi = require('vue-demi');
  4. var idbKeyval = require('idb-keyval');
  5. var __defProp = Object.defineProperty;
  6. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  9. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  10. var __spreadValues = (a, b) => {
  11. for (var prop in b || (b = {}))
  12. if (__hasOwnProp.call(b, prop))
  13. __defNormalProp(a, prop, b[prop]);
  14. if (__getOwnPropSymbols)
  15. for (var prop of __getOwnPropSymbols(b)) {
  16. if (__propIsEnum.call(b, prop))
  17. __defNormalProp(a, prop, b[prop]);
  18. }
  19. return a;
  20. };
  21. function useIDBKeyval(key, initialValue, options = {}) {
  22. const {
  23. flush = "pre",
  24. deep = true,
  25. shallow,
  26. onError = (e) => {
  27. console.error(e);
  28. }
  29. } = options;
  30. const data = (shallow ? vueDemi.shallowRef : vueDemi.ref)(initialValue);
  31. const rawInit = shared.resolveUnref(initialValue);
  32. async function read() {
  33. try {
  34. const rawValue = await idbKeyval.get(key);
  35. if (rawValue === void 0) {
  36. if (rawInit !== void 0 && rawInit !== null)
  37. await idbKeyval.set(key, rawInit);
  38. } else {
  39. data.value = rawValue;
  40. }
  41. } catch (e) {
  42. onError(e);
  43. }
  44. }
  45. read();
  46. async function write() {
  47. try {
  48. if (data.value == null) {
  49. await idbKeyval.del(key);
  50. } else {
  51. if (Array.isArray(data.value))
  52. await idbKeyval.update(key, () => JSON.parse(JSON.stringify(data.value)));
  53. else if (typeof data.value === "object")
  54. await idbKeyval.update(key, () => __spreadValues({}, data.value));
  55. else
  56. await idbKeyval.update(key, () => data.value);
  57. }
  58. } catch (e) {
  59. onError(e);
  60. }
  61. }
  62. vueDemi.watch(data, () => write(), { flush, deep });
  63. return data;
  64. }
  65. exports.useIDBKeyval = useIDBKeyval;