webfansplz / vuejs-challenges

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

18 - useLocalStorage #2697

Open LauGM opened 4 months ago

LauGM commented 4 months ago
<script setup lang='ts'>

import { ref } from "vue"

/**
 * Implement the composable function
 * Make sure the function works correctly
*/
function useLocalStorage(key: string, initialValue: number) {
  console.log('accediendo a use')
  const value = ref(initialValue)
  function set() {
    value.value++;
    const valStr = (value.value).toString();
    localStorage.setItem(key, valStr);
  }
  return { value, set }
}

const {value, set} = useLocalStorage("counter", 0)

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

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

const update = () => {
  set();
}
</script>

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