Last active
June 6, 2022 07:20
-
-
Save JeffreyWay/b6616a64732e2a248e39115714821927 to your computer and use it in GitHub Desktop.
Learn Vue 3, Step By Step: Episode 20 - https://laracasts.com/series/learn-vue-3-step-by-step/episodes/20?reply=18547
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { useStorage } from "@/composables/useStorage"; | |
let food = useStorage('food', 'tacos'); | |
</script> | |
<template> | |
<main> | |
<p> | |
What is your favorite food? <input type="text" v-model="food"> | |
</p> | |
</main> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ref, watch } from "vue"; | |
export function useStorage(key, data = null) { | |
let storedData = read(); | |
if (storedData) { | |
data = ref(storedData); | |
} else { | |
data = ref(data); | |
write(); | |
} | |
watch(data, write, { deep: true }); | |
function read() { | |
return JSON.parse(localStorage.getItem(key)); | |
} | |
function write() { | |
if (data.value === null || data.value === '') { | |
localStorage.removeItem(key); | |
} else { | |
localStorage.setItem(key, JSON.stringify(data.value)); | |
} | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment