Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Last active June 6, 2022 07:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffreyWay/b6616a64732e2a248e39115714821927 to your computer and use it in GitHub Desktop.
Save JeffreyWay/b6616a64732e2a248e39115714821927 to your computer and use it in GitHub Desktop.
<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>
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