Created
March 29, 2020 20:41
-
-
Save ChaDonSom/a61d2d592e06c90be23b77f257c587d2 to your computer and use it in GitHub Desktop.
Use localstorage as a Vue Composition Api ref
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, watch } from '@vue/composition-api' | |
export default key => { | |
let init = localStorage.getItem(key) | |
const variable = ref(init ? JSON.parse(init) : undefined) | |
watch( | |
() => variable.value, | |
to => { | |
localStorage.setItem(key, JSON.stringify(to)) | |
}, | |
{ deep: true } | |
) | |
return variable | |
} |
How about this:
import { ref, watch } from '@vue/composition-api'
export default key => {
const variable = ref(JSON.parse(localStorage.getItem(key) || null))
watch(
variable ,
to => {
localStorage.setItem(key, JSON.stringify(to))
},
{ deep: true }
)
return variable
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be used as: