Last active
November 10, 2020 10:19
-
-
Save jellehak/5a468f118136d469d56f9617722ff201 to your computer and use it in GitHub Desktop.
Simple persistant state in you Vue app
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
export const get = (name = '') => { | |
const storage = localStorage.getItem(name) | |
const resp = JSON.parse(storage) | |
return Array.isArray(resp) ? resp : [] | |
} | |
export const save = (name = '', obj) => { | |
localStorage.setItem(name, JSON.stringify(obj)) | |
} | |
export const usePersist = (name = '') => { | |
return [ | |
() => get(name), | |
(obj) => save(name, obj) | |
] | |
} |
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
<template> | |
<div> | |
<PersistTodo id="list1" /> | |
<PersistTodo id="list2" /> | |
</div> | |
</template> |
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
<script> | |
import { usePersist } from 'usePersist.js' | |
export default { | |
props: { | |
id: { type: String, default: Math.random().toString() } | |
}, | |
data: (vm) => ({ | |
items: [ | |
{ title: 'Item 1' } | |
] | |
}), | |
async mounted () { | |
const [getItems, setItems] = usePersist(this.id) | |
// Watch for changes | |
this.$watch('items', setItems) | |
// Init state | |
this.items = getItems() | |
}, | |
methods: { | |
add () { | |
this.items.push({ title: `Item ${this.items.length + 1}` }) | |
}, | |
onDelete (index) { | |
this.items.splice(index, 1) | |
} | |
} | |
} | |
</script> | |
<template> | |
<div> | |
List #{{ id }} | |
<button @click="add"> | |
Add | |
</button> | |
<div | |
v-for="(item, index) in items" | |
:key="index" | |
> | |
<div> | |
<b>{{ item.title }}</b> | |
<button | |
icon | |
@click="onDelete(item,index)" | |
> | |
delete | |
</button> | |
</div> | |
</div> | |
<div v-if="!items.length"> | |
-- No items -- | |
</div> | |
</div> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment