Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active October 2, 2017 21:23
Show Gist options
  • Save itsMapleLeaf/12d135077cbe15de90ccc107b41dec48 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/12d135077cbe15de90ccc107b41dec48 to your computer and use it in GitHub Desktop.
Simple persistence mixin creator for Vue
function persist(instanceProperty, storageKey) {
return {
created() {
const name = this.$options.name || 'Persistence'
storageKey = storageKey || `__persist__${name}__${instanceProperty}`
this.$watch(instanceProperty, {
deep: true,
handler(value) {
localStorage.setItem(storageKey, JSON.stringify(value))
},
})
try {
this.$set(this, instanceProperty, JSON.parse(localStorage.getItem(storageKey)))
} catch (err) {}
},
}
}
/*
Usage:
export default {
template: `...`,
data() {
return { message: 'This message will persist between page loads!' }
},
mixins: [
persist('message')
]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment