Update State with Vuex Actions in Nuxt.js

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

You can conditionally add classes to Vue.js templates using v-bind:class. This will help display the status of a todo as you add a Vuex action to patch todos. This lesson walks you through setting up a toggle button that triggers a toggle action to patch todos in Vuex.

[00:00] Now, let's go ahead and add another button in here. This one'll be our TOGGLE_TODO, and instead of the trash can we'll use a check mark. You'll see that in action. We have our check marks in there.

[00:11] Then on our actual task name on this span we'll say v-bind:class so that if our todo is complete it'll strike it out. Strike is a class from Tachyons that represents the text-decoration line-through.

[00:27] Let's say todo complete. We'll strike it out if they're complete. None of them are complete right now, so just to make sure this is working I'll say strike it out if it's not complete. That looks like it'll work. Let's wire up this Toggle button. We want to toggle and toggle and duplicate this.

[00:46] Instead of Remove, now we have Toggle, and then instead of Axios Delete we're going to Axios Patch and we'll patch that same ID just like we deleted, but what we're patching this time is the complete to not true but the opposite of what complete currently is. That will toggle it instead of just setting it to true each time.

[01:09] Then we can go ahead and add toggle here as well so that we have a toggle mutation. I'll duplicate this, call this one Toggle, and instead of filtering this time we'll do a map that checks if this todo ID is the same as that todo ID. I'll just do this in a short [inaudible] statement here.

[01:28] If that's true then we want to return this todo. Otherwise return the original todo. Let's make sure this todo is coming back as the right thing, because now we want the response data, not the original one. We'll get the response.data. This is the toggle todo coming back from the patch request.

[01:47] I'll go ahead and save now and if everything's wired up I can check off eating, refresh the page. You'll see that eating is still check off. If I go to Completed, I can check off sleeping. I can delete sleeping.

[01:59] I can toggle back on eating and I can add another task, check that one off, and delete it, and it's toggling simply because we have a button, which when I click toggles it todo and that todo is being passed to Toggle, which is mapped to an action of toggle, which then patches on our API.

[02:19] We get that response back and I commit that response to a toggle mutation, defined here. A todo comes in, and our array of todos just either grabs the original one or if they match it grabs the new or updated one we got from the API response.