ant-design-vue/components/form/demo/global-state.vue

113 lines
2.7 KiB
Vue
Raw Normal View History

2018-05-06 10:32:40 +00:00
<cn>
#### 表单数据存储于上层组件
通过使用 `onFieldsChange` `mapPropsToFields`可以把表单的数据存储到上层组件
**注意**
`mapPropsToFields` 里面返回的表单域数据必须使用 `Form.createFormField` 包装
如果你使用`Form.create`上层组件传递的属性必须在`Form.create({ props: ...})`的props中声明
如果使用`this.$form.createForm`你可以使用任何数据不仅仅局限于上层组件的属性
2018-05-06 10:32:40 +00:00
</cn>
<us>
#### Store Form Data into Upper Component
We can store form data into upper component.
2018-05-08 03:20:07 +00:00
**Note:**
If you use `Form.create`. You must wrap field data with `Form.createFormField` in `mapPropsToFields`.
2018-05-06 10:32:40 +00:00
The properties passed by the upper component must be declared in the props of `Form.create({ props: ...})`.
But if you use `this.$form.createForm`, You can use any data, not just the properties of the upper components.
2018-05-06 10:32:40 +00:00
</us>
2018-05-08 03:20:07 +00:00
<template>
2019-02-01 09:23:00 +00:00
<div id="components-form-demo-global-state">
<customized-form
:username="fields.username"
@change="handleFormChange"
/>
2019-02-01 09:23:00 +00:00
<pre class="language-bash">
{{ JSON.stringify(fields, null, 2) }}
</pre>
</div>
</template>
2018-05-06 10:32:40 +00:00
<script>
const CustomizedForm = {
props: ['username'],
template: `
<a-form layout='inline' :form="form">
<a-form-item label='Username'>
<a-input
v-decorator="[
'username',
{
rules: [{ required: true, message: 'Username is required!' }],
}
]"
/>
</a-form-item>
</a-form>
`,
created () {
this.form = this.$form.createForm(this, {
2019-04-20 06:19:13 +00:00
name: 'global_state',
onFieldsChange: (_, changedFields) => {
2019-01-12 03:33:27 +00:00
this.$emit('change', changedFields);
},
mapPropsToFields: () => {
return {
username: this.$form.createFormField({
...this.username,
value: this.username.value,
}),
2019-01-12 03:33:27 +00:00
};
},
onValuesChange (_, values) {
2019-01-12 03:33:27 +00:00
console.log(values);
},
2019-01-12 03:33:27 +00:00
});
2018-05-06 10:32:40 +00:00
},
watch: {
username () {
this.form.updateFields({
username: this.$form.createFormField({
...this.username,
value: this.username.value,
}),
2019-01-12 03:33:27 +00:00
});
},
2018-05-06 10:32:40 +00:00
},
2019-01-12 03:33:27 +00:00
};
2018-05-06 10:32:40 +00:00
export default {
2019-02-01 09:23:00 +00:00
components: {
CustomizedForm,
},
2018-05-06 10:32:40 +00:00
data () {
return {
fields: {
username: {
value: 'benjycui',
},
},
2019-01-12 03:33:27 +00:00
};
2018-05-06 10:32:40 +00:00
},
methods: {
handleFormChange (changedFields) {
2019-01-12 03:33:27 +00:00
console.log('changedFields', changedFields);
this.fields = { ...this.fields, ...changedFields };
2018-05-06 10:32:40 +00:00
},
},
2019-01-12 03:33:27 +00:00
};
2018-05-06 10:32:40 +00:00
</script>
<style>
#components-form-demo-global-state .language-bash {
max-width: 400px;
border-radius: 6px;
margin-top: 24px;
}
</style>
2018-05-08 03:20:07 +00:00
2018-05-06 10:32:40 +00:00