Last active
November 14, 2022 13:59
-
-
Save smorcuend/580f886dbf45eb8a64fe8a626b870f7c to your computer and use it in GitHub Desktop.
Nuxt3 Composables advanced usage - Immutability
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> | |
<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> |
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 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