Last active
November 18, 2018 13:46
-
-
Save dmorrison42/65b650ca81d7d98236c7fad2494ef402 to your computer and use it in GitHub Desktop.
Quick and dirty persistence in Vue (for development with LiveServer)
This file contains 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
/* Usage: Import after Vue but before `new Vue` | |
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> | |
<script src="auto-persist.js"></script> | |
... | |
<script src="script.js"></script> | |
*/ | |
Vue.use({ | |
install(Vue) { | |
const storageName = 'storage'; | |
let restored = false; | |
function getData(vueElement) { | |
return { | |
$data: vueElement.$data, | |
$children: vueElement.$children.map(getData), | |
} | |
} | |
// TODO: Save only the data that has updated | |
function saveData(obj, data) { | |
if (!restored) return; | |
const saveData = getData(obj.$root); | |
sessionStorage.setItem(storageName, JSON.stringify(saveData)); | |
} | |
function restoreData(obj, data) { | |
return new Promise((resolve) => { | |
if (obj == null || data == null) { | |
resolve(); | |
return; | |
} | |
const keys = Object.keys(data.$data); | |
for (let i = 0; i < keys.length; i++) { | |
obj[keys[i]] = data.$data[keys[i]]; | |
} | |
obj.$nextTick(() => { | |
Promise.all(obj.$children | |
.map((_, i) => restoreData( | |
obj.$children[i], | |
data.$children[i]))) | |
.then(() => resolve()); | |
}); | |
}); | |
} | |
Vue.mixin({ | |
mounted() { | |
this.$nextTick(() => { | |
if (this.$parent != null || restored) return; | |
const saveData = sessionStorage.getItem(storageName); | |
restoreData(this, JSON.parse(saveData || 'null')) | |
.then(() => { restored = true; }); | |
}); | |
saveData(this, this.$data); | |
this.$watch('$data', (newData) => { | |
saveData(this, newData); | |
}, { deep: true }); | |
} | |
}); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment