Session storage used to save tile collapse state

This commit is contained in:
Alicia Sykes 2019-09-06 15:00:15 +01:00
parent 45edb85b36
commit 0797377eb4
2 changed files with 40 additions and 2 deletions

View File

@ -6,7 +6,7 @@
"start": "node server",
"dev": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
"lint": "vue-cli-service lint --fix"
},
"dependencies": {
"connect": "^3.7.0",

View File

@ -4,7 +4,8 @@
:id="`collapsible-${uniqueKey}`"
class="toggle"
type="checkbox"
:checked="!collapsed">
:checked="getCollapseState()"
@change="collapseChanged">
<label :for="`collapsible-${uniqueKey}`" class="lbl-toggle" tabindex="0">
<h2>{{ title }}</h2>
</label>
@ -24,6 +25,43 @@ export default {
title: String,
collapsed: Boolean,
},
data() {
return {
isOpen: !this.collapsed,
};
},
methods: {
initialiseStorage() {
const initStorage = () => localStorage.setItem('collapseState', JSON.stringify({}));
if (!localStorage.collapseState) initStorage(); // If not yet set, then init localstorage
try { // Check storage is valid JSON, and has not been corrupted
JSON.parse(localStorage.collapseState);
} catch {
initStorage();
}
return JSON.parse(localStorage.collapseState);
},
getCollapseState() {
const collapseStateObject = this.initialiseStorage();
let collapseState = !this.collapsed;
if (collapseStateObject[this.uniqueKey] !== undefined) {
collapseState = collapseStateObject[this.uniqueKey];
}
return collapseState;
},
setCollapseState(id, newState) {
// Get the current localstorage collapse state object
const collapseState = JSON.parse(localStorage.collapseState);
// Add the new state to it
collapseState[id] = newState;
// Stringify, and set the new object into local storage
localStorage.setItem('collapseState', JSON.stringify(collapseState));
},
collapseChanged(whatChanged) {
this.initialiseStorage();
this.setCollapseState(this.uniqueKey.toString(), whatChanged.srcElement.checked);
},
},
};
</script>