Created
November 4, 2020 14:47
-
-
Save jakedohm/1518c87d6529315893c9e98eb19a5722 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
import { usePersistedRef } from "./usePersistentRef"; | |
export default { | |
setup() { | |
const name = usePersistedRef('name', 'Jake Dohm') | |
} | |
} | |
</script> |
This file contains hidden or 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, watchEffect } from 'vue' | |
export function usePersistedRef(key, initialValue) { | |
// Check if value exists in localStorage | |
// If it doesn't, then we need to initialize it using the initialValue argument | |
const persistedValue = window.localStorage.getItem(key) | |
const value = persistedValue ? JSON.parse(persistedValue) : initialValue | |
const persistentRef = ref(value) | |
// Save new value of ref to localStorage whenever it changes | |
watchEffect(() => { | |
window.localStorage.setItem(key, JSON.stringify(persistentRef.value)) | |
}) | |
// Return ref (reactive value) | |
return persistentRef | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment