vhook

useStorage


提供具备响应式的 localStoragesessionStorage 状态

API

const [state, setState] = useStorage(key, val, storage)

Params

参数名描述类型默认值
key存进 localStoragesessionStorage 中的 keystring
val存进 localStoragesessionStorage 中的 val,会使用 JSON.stringify 进行序列化any
storage要使用的存储方式StoragelocalStorage

Result

参数名描述类型
state存进 localStoragesessionStorage 中的 val,从 localStorage 中取出时会进行 JSON.parse 反序列化, 只读DeepReadonly<Ref<T | null>>
setState更新 localStoragesessionStorage,同时 state 也会更新, 不传参数则等同于 removeItem(Val?: T) => void

Example

Code

<template>
  <div>
    <p>将数据持久化到 localStorage 中</p>
    <p>localStorage中的值: {{localStorageState}}</p>
    <p>刷新页面能拿到存在 localStorage 中的状态</p>
    <input v-model="value"/>
    <button @click="updateLocalStorage(value)">update</button>
    <button @click="updateLocalStorage()">remove</button>
  </div>
  <div>
    <p>将数据持久化到 sessionStorage 中</p>
    <p>sessionStorage中的值: {{sessionStorageState}}</p>
    <p>刷新页面能拿到存在 sessionStorage 中的状态</p>
    <input v-model="val"/>
    <button @click="updateSessionStorage(val)">update</button>
    <button @click="updateSessionStorage()">remove</button>
  </div>
</template>

<script>
  import { useStorage } from 'vhook'
  import { ref } from 'vue'
  export default {
    setup () {
      const [localStorageState, updateLocalStorage] = useStorage('a', 'localStorage')
      const [sessionStorageState, updateSessionStorage] = useStorage('b', 'sessionStorage', sessionStorage)
      const value = ref(localStorageState.value)
      const val = ref(sessionStorageState.value)
      return {
        localStorageState,
        sessionStorageState,
        value,
        val,
        updateLocalStorage,
        updateSessionStorage
      }
    }
  }
</script>