Problem
I am learning Vue.JS and I’m creating a simple todo app, where each list has a unique id. I am iterating through all of the list to create a Vue instance:
<div id="todo-list-1" class="todo-list">...</div>
<div id="todo-list-2" class="todo-list">...</div>
<div id="todo-list-3" class="todo-list">...</div>
// main.js
document.querySelectorAll('.todo-list').forEach(list => {
new Vue({
el: `#${list.id}`,
render: h => h(App)
})
})
I want to create a “completed” state, which would be true when all items in a list are completed. So #todo-list-1
has a completed state, same with #todo-list-2
and #todo-list-3
.
What would be a good approach to this problem? how can I handle the state for individual vue instances?
Solution
I consider Vuex advanced state management, and for the sake of your simple application I, personally, would value a simpler data-centric approach.
To this end, I propose you focus on creating a single instance that can have multiple todo-lists inside it represented as components.
<div id="app">
<TodoList v-for="list in lists" :key="list.id" />
</div>
data() {
return {
lists: [
{
id: 1,
todos: []
},
// ...
]
}
}
Obviously, you’d need to represent your todos as a list of todo lists (with todos inside). You’ll also need to ensure correct state management but JavaScripts pass-by-reference for objects will save you time here.
In order to detect if all todos are completed you could add a getter into the root instance to detect them all, or in the component to detect them per-instance.
I hope this helps set you on the right path, the best thing to do in most cases is start with your data-model as Vue is a data-centric framework.