webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

18 - 实现本地存储函数 #2724

Open Ly-TiR opened 2 months ago

Ly-TiR commented 2 months ago
<script setup lang='ts'>

import {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()
        return localStorage.getItem(key) ?? initialValue
      },
      set(newVal){
        trigger()
        localStorage.setItem(key,newVal)
      }
    }
  })

  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>