The default behavior of submitting an HTML form is to reload the page. You can use the Vue.js @submit.prevent
syntax to avoid that behavior. Then wire together the @submit
event with an add
Vuex action to handle an async post to an api. This lesson walks you through posting to an API using Vue.js, Vuex. and Nuxt.
Notice that after reload the page, when the form submit, the page reloads.
To prevent page reloads every time we submit the form we can use:
To deal with the store, we can use 'actions' in Vuex.Store and 'mapActions' helpers:
- { {todo.task}}
We change form submit to:
The 'add' method map to action in store:
import Vuex from 'vuex'import axios from 'axios'const store = () => new Vuex.Store({ state: { todos: [ ] }, mutations: { init (state, todos) { state.todos = todos }, add (state, todo) { state.todos = [ ...state.todos, todo ] } }, actions: { async add (context, task) { const commit = context.commit const res = await axios.post('https://todos-cuvsmolowg.now.sh/todos', { task, complete: false }) commit('add', res.data) } }})export default store
Inside, add function, we post the data to the backend, then we can use 'commit' method to mutate the data in the store.