博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Nuxt] Build a Vue.js Form then use Vuex Actions to Post to an API in Nuxt
阅读量:5278 次
发布时间:2019-06-14

本文共 1520 字,大约阅读时间需要 5 分钟。

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 @submitevent 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:

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.

 

转载于:https://www.cnblogs.com/Answer1215/p/7236441.html

你可能感兴趣的文章
SetCapture() & ReleaseCapture() 捕获窗口外的【松开左键事件】: WM_LBUTTONUP
查看>>
Android 设置界面的圆角选项
查看>>
百度地图api服务端根据经纬度得到地址
查看>>
CSS中隐藏内容的3种方法及属性值
查看>>
每天一个linux命令(1):ls命令
查看>>
根据xml生成相应的对象类
查看>>
查看ASP.NET : ViewState
查看>>
Android StageFrightMediaScanner源码解析
查看>>
vue项目中开启Eslint碰到的一些问题及其规范
查看>>
循环队列实现
查看>>
CSS层模型
查看>>
springBoot 项目 jar/war打包 并运行
查看>>
HDU 1501 Zipper
查看>>
打包java程序生成exe
查看>>
八叉树
查看>>
poj 1129 搜索
查看>>
Git 远程仓库
查看>>
HttpClient的巨坑
查看>>
关于静态文本框透明度的问题
查看>>
海量数据、高并发的优化方案
查看>>