mjk*_*kim 10 forms vue.js vuex
我有一个大表单在单页提交.
<container>
<formA>
<formB>
<formC>
<submitButton>
<container>
Run Code Online (Sandbox Code Playgroud)
看起来很像这样.我有一个存储每个表单数据的商店.然后当用户点击提交按钮时,我使用vuex商店收集所有表单数据.
问题是我需要每次都在商店中更新表单数据.
所以我会在vue组件中这样
watch: {
userInput (val) {
this.updateState(val)
}
Run Code Online (Sandbox Code Playgroud)
通过观察表单数据(与v模型绑定)输入更改时更新状态.
或者像vuex doc中记录的那样.
userInput: {
get () {
return this.$store.state.userInput
},
set (val) {
this.updateState(val)
}
}
Run Code Online (Sandbox Code Playgroud)
好吧..我认为这些都不是好主意.有没有更好的方法来形成vuex处理?
我制作了一个小工具,可以简化使用Vuex的表单处理:vuex-map-fields
import Vue from 'vue';
import Vuex from 'vuex';
// Import the `getField` getter and the `updateField`
// mutation function from the `vuex-map-fields` module.
import { getField, updateField } from 'vuex-map-fields';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
fieldA: '',
fieldB: '',
},
getters: {
// Add the `getField` getter to the
// `getters` of your Vuex store instance.
getField,
},
mutations: {
// Add the `updateField` mutation to the
// `mutations` of your Vuex store instance.
updateField,
},
});
Run Code Online (Sandbox Code Playgroud)
<template>
<div id="app">
<input v-model="fieldA">
<input v-model="fieldB">
</div>
</template>
<script>
import { mapFields } from 'vuex-map-fields';
export default {
computed: {
// The `mapFields` function takes an array of
// field names and generates corresponding
// computed properties with getter and setter
// functions for accessing the Vuex store.
...mapFields([
'fieldA',
'fieldB',
]),
},
};
</script>
Run Code Online (Sandbox Code Playgroud)
您可以在我的博客上阅读有关vuex-map-fields的更多信息:如何使用Vue,Vuex和vuex-map-fields处理多行表单
小智 0
我对这个问题很头疼。
Vuex 文档描述我们需要更新每个字段的存储。打字这么费力有啥用?
我们制定了一种有效的解决方案。它基于将存储对象克隆到本地。
//We are passing (vuexstore) 'item' object from parent component:
//<common-item v-bind:item="item" ....
props: ['item'],
// create localItem - this is reactive object for vuex form
data: () => {
return {
localItem: null
}
},
// make clone on created event
created: function() {
this.localItem = this._clone(this.item)
},
// watch vuexstore 'item' for changes
watch: {
item: function(val) {
this.localItem = this._clone(this.item)
}
},
// map mutations and update store on event
methods: {
...mapMutations([
'editItem'
]),
updateItemHandler: function() {
this.editItem({ item: this._clone(this.localItem) })
},
_clone: function(o){
return JSON.parse(JSON.stringify(o))
}
},
Run Code Online (Sandbox Code Playgroud)
内部表格使用:
<input v-model="localItem.text" @keyup="updateItemHandler" type="text" class="form-control"></input>
Run Code Online (Sandbox Code Playgroud)
我认为这只是缺少vuex。应该有更短的内置解决方案。
| 归档时间: |
|
| 查看次数: |
5102 次 |
| 最近记录: |