Skip to content

Commit

Permalink
add some vuex mutations and actions
Browse files Browse the repository at this point in the history
  • Loading branch information
davidgaroro committed Apr 16, 2021
1 parent 80aa8f4 commit 8a9ebc1
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
6 changes: 6 additions & 0 deletions src/components/TodoItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,22 @@
type="button"
class="btn-close btn-sm ms-2"
aria-label="Remove todo"
@click="removeTodo(todo)"
></button>
</li>
</template>

<script>
import { mapActions } from "vuex";
export default {
name: "TodoItem",
props: {
todo: Object,
},
methods: {
...mapActions(["removeTodo"]),
},
};
</script>

Expand Down
30 changes: 28 additions & 2 deletions src/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,35 @@ const state = {
],
};

// mutations
const mutations = {
addTodo(state, todo) {
state.todos.push(todo);
},

removeTodo(state, todo) {
state.todos.splice(state.todos.indexOf(todo), 1);
},
};

// actions
const actions = {
addTodo({ commit }, text) {
commit("addTodo", {
id: Date.now(),
text,
done: false,
});
},

removeTodo({ commit }, todo) {
commit("removeTodo", todo);
},
};

export default createStore({
state,
mutations: {},
actions: {},
mutations,
actions,
modules: {},
});
13 changes: 13 additions & 0 deletions src/views/Home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
autocomplete="off"
aria-label="New todo text"
placeholder="What needs to be done?"
@keyup.enter="addTodo"
/>
<ul class="list-group">
<TodoItem v-for="todo in todos" :key="todo.id" :todo="todo" />
Expand All @@ -27,5 +28,17 @@ export default {
return this.$store.state.todos;
},
},
methods: {
addTodo(e) {
const text = e.target.value;
if (text.trim()) {
// Add new todo
this.$store.dispatch("addTodo", text);
// Clear input text
e.target.value = "";
}
},
},
};
</script>

0 comments on commit 8a9ebc1

Please sign in to comment.