This example shows a simple todo list using a Pinia store. You can add todos and toggle their done status. The store keeps the list and updates it for the app.
import { createApp, ref } from 'vue'
import { createPinia, defineStore } from 'pinia'
// Create a store
export const useTodoStore = defineStore('todo', {
state: () => ({
todos: []
}),
actions: {
addTodo(text) {
this.todos.push({ text, done: false })
},
toggleTodo(index) {
this.todos[index].done = !this.todos[index].done
}
}
})
// Vue app component
const App = {
template: `
<div>
<h1>Todo List</h1>
<input v-model="newTodo" @keyup.enter="add" placeholder="Add todo" aria-label="Add todo" />
<ul>
<li v-for="(todo, i) in todoStore.todos" :key="i">
<label>
<input type="checkbox" v-model="todo.done" />
<span :style="{ textDecoration: todo.done ? 'line-through' : 'none' }">{{ todo.text }}</span>
</label>
</li>
</ul>
</div>
`,
setup() {
const todoStore = useTodoStore()
const newTodo = ref('')
function add() {
if (newTodo.value.trim()) {
todoStore.addTodo(newTodo.value.trim())
newTodo.value = ''
}
}
return { todoStore, newTodo, add }
}
}
// Create app and use Pinia
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')