Skip to content

Instantly share code, notes, and snippets.

@jakedohm
Created November 4, 2020 14:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakedohm/1518c87d6529315893c9e98eb19a5722 to your computer and use it in GitHub Desktop.
Save jakedohm/1518c87d6529315893c9e98eb19a5722 to your computer and use it in GitHub Desktop.
<script>
import { usePersistedRef } from "./usePersistentRef";
export default {
setup() {
const name = usePersistedRef('name', 'Jake Dohm')
}
}
</script>
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