Skip to content

Instantly share code, notes, and snippets.

@ChaDonSom
Created March 29, 2020 20:41
Show Gist options
  • Save ChaDonSom/a61d2d592e06c90be23b77f257c587d2 to your computer and use it in GitHub Desktop.
Save ChaDonSom/a61d2d592e06c90be23b77f257c587d2 to your computer and use it in GitHub Desktop.
Use localstorage as a Vue Composition Api ref
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
}
@zRains
Copy link

zRains commented Feb 14, 2022

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