Skip to content

可以双向绑定的dbStorage

此hook适用于vue3,可以将dbStorage的数据变为双向绑定的数据。

使用方法

typescript
import {useUtoolsDbStorage} from '@/hooks/useUtoolsDbStorage'

const store = useUtoolsDbStorage('/key/shi-ci', '');

console.log(store.value)

代码

typescript
import { ref, Ref, shallowRef, toRaw, watch } from "vue";

export interface UseUtoolsDbOptions {
  flush?: 'pre' | 'post' | 'sync';
  deep?: boolean;
  shallow?: boolean;

  onError?(e: any): void;
}

/**
 * 异步对象存储
 */
export function useUtoolsDbStorage<T extends (string | number | boolean | object | null)>(
  key: string,
  initialValue: T,
  options: UseUtoolsDbOptions = {},
): Ref<T> {
  const {
    flush = 'pre',
    deep = true,
    shallow,
    onError = (e) => {
      console.error('数据保存失败', e)
    },
  } = options

  const sourceValue = utools.dbStorage.getItem(key);

  const data = (shallow ? shallowRef : ref)((typeof sourceValue === 'undefined' || sourceValue === null) ? initialValue : sourceValue) as Ref<T>

  watch(
    data,
    (val) => {
      try {
        if (data.value == null)
          utools.dbStorage.removeItem(key)
        else
          utools.dbStorage.setItem(key, toRaw(data.value))
      } catch (e) {
        onError(e)
      }
    },
    {
      flush,
      deep,
    },
  )

  return data as Ref<T>
}
javascript
import { ref, Ref, shallowRef, toRaw, watch } from "vue";


/**
 * 异步对象存储
 * @param key {string} 键
 * @param initialValue {string | number | boolean | object | null} 初始值
 * @param [options] {{
 flush?: 'pre' | 'post' | 'sync';
 deep?: boolean;
 shallow?: boolean;

 onError?(e: any): void;
 }} 参数配置
 */
export function useUtoolsDbStorage(
    key,
    initialValue,
    options = {}
): Ref {
    const {
        flush = 'pre',
        deep = true,
        shallow,
        onError = (e) => {
            console.error('数据保存失败', e)
        },
    } = options

    const sourceValue = utools.dbStorage.getItem(key);

    const data = (shallow ? shallowRef : ref)((typeof sourceValue === 'undefined' || sourceValue === null) ? initialValue : sourceValue);

        watch(
            data,
            (val) => {
                try {
                    if (data.value == null)
                        utools.dbStorage.removeItem(key)
                    else
                        utools.dbStorage.setItem(key, toRaw(data.value))
                } catch (e) {
                    onError(e)
                }
            },
            {
                flush,
                deep,
            },
        )

    return data;
}