-
-
Notifications
You must be signed in to change notification settings - Fork 202
Open
Description
<script setup lang='ts'>
import { customRef } from "vue"
/**
* Implement the composable function
* Make sure the function works correctly
*/
function useLocalStorage<T>(key: string, initialValue: any) {
return customRef<T>((track, trigger) => ({
get: () => {
track()
return JSON.parse(localStorage.getItem(key)) ?? initialValue
},
set: (value) => {
trigger()
localStorage.setItem(key, JSON.stringify(value))
}
}))
}
const counter = useLocalStorage<Number>("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>