[NUXT] Use Vuex Actions to Delete Data from APIs in Nuxt and Vue.js

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.