You'll begin to notice as your build out your actions in Vuex, many of them would look quite similar. Creating a remove action looks almost the same as the add action except for using the axios.delete
method then filtering out the Deleted Todo Once the response comes back.
Add A Remove button to the Todo list:
<Template> <Div> <form@submit. Prevent= "Add (Task)"> <inputV-model= "task"type= "text" /> <inputtype= "Submit"value= "ADD"> </form> <articleclass= "Pa3 pa5-ns"> <ulclass= "List pl0 ml0 center mw6 ba b--light-silver br2"> <Liv-for= "Todo of Todos"class= "Flex items-center ph3 pv3 bb b--light-silver"> <spanclass= "Flex-auto">{{Todo.id}} {{Todo.task}}</span> <Button@click= "remove(TODO)"><imgsrc= "Https://icon.now.sh/trash"alt= "Delete"></Button> </Li> </ul> </article> </Div></Template><Script>Import {mapstate, mapactions} from'Vuex'Import {init} from'./shared'Exportdefault{fetch:init, computed: {... mapstate ({todos: (state)=State.todos})}, data () {return{task:'Some Data'}}, Methods: {... mapactions (['Add', 'Remove' ]) } }</Script>
Store/index.js:
Import Vuex from 'Vuex'Import Axios from 'Axios'Conststore = () =NewVuex.store ({state: {todos: []}, Mutations: {init (state, Todos) {State.todos=Todos}, add (state, Todo) {State.todos=[... state.todos, Todo]}, remove (state, Todo) {State.todos= State.todos.filter ((t) = = { returnT.id!==todo.id})}}, actions: {AsyncAdd (context, Task) {Constcommit =Context.commitConstres =awaitAxios.post ('Https://todos-cuvsmolowg.now.sh/todos', {task, complete:false}) Commit ('Add', Res.data)},Asyncremove ({commit}, Todo) {awaitAxios.delete (' https://todos-cuvsmolowg.now.sh/todos/${todo.id} ')Commit'Remove', Todo)} }}) ExportdefaultStore
[NUXT] Use Vuex Actions to Delete Data from APIs in Nuxt and Vue.js