Closed
Description
<script setup lang="ts">
import { ref, computed } from 'vue';
/**
* Implement the composable function
* Make sure the function works correctly
*/
function useLocalStorage(key: string, initialValue: any) {
const state = ref(initialValue);
const storedValue = localStorage.getItem(key);
if (storedValue !== null) {
state.value = JSON.parse(storedValue);
} else {
localStorage.setItem(key, JSON.stringify(initialValue));
}
const storageComputed = computed({
get() {
return state.value;
},
set(newValue) {
state.value = newValue;
localStorage.setItem(key, JSON.stringify(newValue));
},
});
return storageComputed;
}
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>