Last active
October 2, 2017 21:23
-
-
Save itsMapleLeaf/12d135077cbe15de90ccc107b41dec48 to your computer and use it in GitHub Desktop.
Simple persistence mixin creator for Vue
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
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