Skip to content

Instantly share code, notes, and snippets.

@smorcuend
Last active November 14, 2022 13:59
Show Gist options
  • Save smorcuend/580f886dbf45eb8a64fe8a626b870f7c to your computer and use it in GitHub Desktop.
Save smorcuend/580f886dbf45eb8a64fe8a626b870f7c to your computer and use it in GitHub Desktop.
Nuxt3 Composables advanced usage - Immutability
<template>
<div>
<input type="text" v-model="newTodo" />
<button
@click="
addToDo(newTodo);
newTodo = '';
"
>
Add ToDo
</button>
<ul>
<li v-for="t in toDo">
{{ t }} <button @click="removeToDo(t)">X</button>
</li>
</ul>
</div>
</template>
<script setup>
const { toDo, addToDo, removeToDo } = useToDo()
const newTodo = ref()
</script>
export type ToDo = string
export default function () {
const toDo = useState<ToDo[]>('toDo', () => [])
const hasToDo = (thing: string) => toDo.value.includes(thing)
const addToDo = (thing: string) => {
if (!hasToDo(thing)) toDo.value.push(thing)
}
const removeToDo = (thing: string) => {
const index = toDo.value.indexOf(thing);
if (index !== -1) {
toDo.value.splice(index, 1);
}
}
return {
toDo: readonly(toDo),
hasToDo,
addToDo,
removeToDo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment