useLocalStorage

一个可以将状态持久化存储在 localStorage 中的 Hook 。

使用Demo

<template>
  <div class="hello" style="display:flex;align-items:flex-start;">
    <div style="width: 60vw">
      <p> value:{{ state }}</p>
    </div>
    <div style="width:39vw">
      <button @click="handleUpdate">更新storage</button>
      <button @click="handleDelete">删除storage</button>
    </div>
  </div>
</template>

<script lang="ts">
import { useLocalStorage } from "v3hooks";

export default {
  props: {
    msg: String,
  },
  setup() {
    const state = useLocalStorage('useLocalStorage',{a:231});

    const handleUpdate = ()=>{
        state.value = { a: Math.random()};
    };

    const handleDelete = ()=>{
        state.value = undefined;
    };

    // useVirtualList测试
    return {
      state,
      handleUpdate,
      handleDelete
    };
  },
};
</script>

useLocalStorage接受一个key和一个value,导出一个响应式的state, 用户直接赋值state.value可自动修改本地localStorage。

注意点

  • 不设置value可用于获取本地LocalStorage 例:useLocalStorage('useLocalStorage')

  • value等于undefined或者null可用于删除本地Storage 例:state.value = undefined;

Api

const state = useLocalStorage(
  key: string,
  initialValue?: any,
  options?: Options
);

Params

Options

Result

最后更新于