Skip to content

Instantly share code, notes, and snippets.

@jellehak
Last active November 10, 2020 10:19
Show Gist options
  • Save jellehak/5a468f118136d469d56f9617722ff201 to your computer and use it in GitHub Desktop.
Save jellehak/5a468f118136d469d56f9617722ff201 to your computer and use it in GitHub Desktop.
Simple persistant state in you Vue app
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)
]
}
<template>
<div>
<PersistTodo id="list1" />
<PersistTodo id="list2" />
</div>
</template>
<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