persistent-state

simple state manager based on Vue3.reactive and localStorage

当前为 2024-05-06 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name persistent-state
  3. // @description simple state manager based on Vue3.reactive and localStorage
  4. // @namespace http://tampermonkey.net/
  5. // @author smartacephale
  6. // @license MIT
  7. // @version 1.0
  8. // @match *://*/*
  9. // ==/UserScript==
  10. /* globals reactive, watch */
  11.  
  12. class PersistentState {
  13. constructor(state, key = "state_acephale") {
  14. this.key = key;
  15. this.state = reactive(state);
  16. this.sync();
  17. this.watchPersistence();
  18. }
  19.  
  20. sync() {
  21. this.trySetFromLocalStorage();
  22. window.addEventListener('focus', this.trySetFromLocalStorage);
  23. }
  24.  
  25. watchPersistence() {
  26. watch(this.state, (value) => {
  27. this.saveToLocalStorage(this.key, value);
  28. });
  29. }
  30.  
  31. saveToLocalStorage(key, value) {
  32. localStorage.setItem(key, JSON.stringify(value));
  33. }
  34.  
  35. trySetFromLocalStorage = () => {
  36. const localStorageValue = localStorage.getItem(this.key);
  37. if (localStorageValue !== null) {
  38. const prevState = JSON.parse(localStorageValue);
  39. for (const prop of Object.keys(prevState)) {
  40. this.state[prop] = prevState[prop];
  41. }
  42. }
  43. }
  44. }