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

18 - 实现本地存储函数

Open GISzgj opened this issue 1 year ago • 2 comments

<script setup lang='ts'>
import { ref, customRef } from "vue"

/**
 * Implement the composable function
 * Make the function work fine
*/
function useLocalStorage(key: string, initialValue: any) {
  const value = customRef((track, trigger) =>{
    return {
      get(){
        track()
        return localStorage.getItem(key) ?? initialValue
      },
      set(nval){
        trigger()
        localStorage.setItem(key, nval)
      }
    }
  })
  return value
}

const counter = useLocalStorage("counter", 0)

// We can get localStorage via triggered the getter:
console.log(counter.value)

// And We also can set localStorage via triggered the setter:
const update = () => counter.value++
  
</script>


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

GISzgj avatar Dec 08 '23 03:12 GISzgj

cool

undefined-zzk avatar Jan 28 '24 10:01 undefined-zzk