vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

18 - 实现本地存储函数

Open shenrui1 opened this issue 1 year ago • 0 comments

// 你的答案

<script setup lang='ts'>

import { ref, customRef } from "vue"

/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useLocalStorage(key: string, initialValue: any) {
  const value = customRef((track, trigger) => {
    return {
      get() {
        track()
        if(!localStorage.getItem(key)) {
          localStorage.setItem(key, initialValue)
        }
        return localStorage.getItem(key)
      },
      set(val) {
        localStorage.setItem(key, val)
        trigger()
      }
    }
  })

  return value
}

const counter = useLocalStorage("counter", 0)

// We can get localStorage by triggering the getter:
console.log(counter.value)

// And we can also set localStorage by triggering the setter:

const update = () => counter.value++

</script>

<template>
  <p>Counter: {{ counter }}</p>
  <button @click="update">
    Update
  </button>
</template>

shenrui1 avatar Jan 17 '24 11:01 shenrui1