ant-design-vue/components/form/demo/vuex.vue

87 lines
2.0 KiB
Vue
Raw Normal View History

2019-02-11 14:22:15 +00:00
<cn>
#### 表单数据存储于 Vuex Store
通过使用 onFieldsChange mapPropsToFields可以把表单的数据存储到 Vuex
**注意**
`mapPropsToFields` 里面返回的表单域数据必须使用 `Form.createFormField` 包装
</cn>
<us>
#### Store Form Data into Vuex Store
We can store form data into Vuex Store.
**Note:**
You must wrap field data with `Form.createFormField` in `mapPropsToFields`.
</us>
<template>
<div id="components-form-demo-vuex">
2019-09-28 12:45:07 +00:00
<a-form :form="form" @submit="handleSubmit">
2019-02-11 14:22:15 +00:00
<a-form-item label="Username">
<a-input
v-decorator="[
'username',
{
rules: [{ required: true, message: 'Username is required!' }],
2019-09-28 12:45:07 +00:00
},
2019-02-11 14:22:15 +00:00
]"
/>
</a-form-item>
2019-09-28 12:45:07 +00:00
<a-button type="primary" html-type="submit">
2019-02-11 14:22:15 +00:00
Submit
</a-button>
</a-form>
</div>
</template>
<script>
2019-09-28 12:45:07 +00:00
export default {
2019-02-11 14:22:15 +00:00
computed: {
2019-09-28 12:45:07 +00:00
username() {
2019-02-11 14:22:15 +00:00
return this.$store.state.username;
},
},
watch: {
2019-09-28 12:45:07 +00:00
username(val) {
2019-02-11 14:22:15 +00:00
console.log('this.$store.state.username: ', val);
2019-09-28 12:45:07 +00:00
this.form.setFieldsValue({ username: val });
2019-02-11 14:22:15 +00:00
},
},
2019-09-28 12:45:07 +00:00
created() {
2019-02-11 14:22:15 +00:00
this.form = this.$form.createForm(this, {
onFieldsChange: (_, changedFields) => {
this.$emit('change', changedFields);
},
mapPropsToFields: () => {
return {
username: this.$form.createFormField({
value: this.username,
}),
};
},
2019-09-28 12:45:07 +00:00
onValuesChange: (_, values) => {
2019-02-11 14:22:15 +00:00
console.log(values);
2019-09-28 12:45:07 +00:00
// Synchronize to vuex store in real time
2019-02-11 14:22:15 +00:00
// this.$store.commit('update', values)
},
});
},
methods: {
2019-09-28 12:45:07 +00:00
handleSubmit(e) {
2019-02-11 14:22:15 +00:00
e.preventDefault();
this.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
this.$store.commit('update', values);
}
});
},
},
};
</script>
<style>
#components-form-demo-vuex .language-bash {
max-width: 400px;
border-radius: 6px;
margin-top: 24px;
}
</style>