feat(Form): binding checkbox

This commit is contained in:
陈嘉涵 2020-02-10 10:57:57 +08:00
parent f385c94040
commit 1fe96f3edc
5 changed files with 32 additions and 4 deletions

View File

@ -15,6 +15,12 @@ const [createComponent, bem] = createNamespace('field');
export default createComponent({ export default createComponent({
inheritAttrs: false, inheritAttrs: false,
provide() {
return {
vanField: this,
};
},
inject: { inject: {
vanForm: { vanForm: {
default: null, default: null,
@ -111,6 +117,10 @@ export default createComponent({
return { width: addUnit(labelWidth) }; return { width: addUnit(labelWidth) };
} }
}, },
formValue() {
return this.children ? this.children.value : this.value;
},
}, },
methods: { methods: {
@ -135,7 +145,7 @@ export default createComponent({
} }
return !this.rules.some(rule => { return !this.rules.some(rule => {
if (rule.required && !this.value) { if (rule.required && !this.formValue) {
this.validateMessage = rule.message; this.validateMessage = rule.message;
return true; return true;
} }

View File

@ -17,7 +17,11 @@
:rules="[{ required: true, message: 'password is required' }]" :rules="[{ required: true, message: 'password is required' }]"
placeholder="password" placeholder="password"
/> />
<van-field name="agree" label="agree"> <van-field
name="agree"
label="agree"
:rules="[{ required: true, message: 'need agree' }]"
>
<van-checkbox v-model="agree" slot="input" shape="square" /> <van-checkbox v-model="agree" slot="input" shape="square" />
</van-field> </van-field>
<van-button type="primary">submit</van-button> <van-button type="primary">submit</van-button>

View File

@ -24,7 +24,7 @@ export default createComponent({
getFormData() { getFormData() {
return this.fields.reduce((form, field) => { return this.fields.reduce((form, field) => {
form[field.name] = field.value; form[field.name] = field.formValue;
return form; return form;
}, {}); }, {});
}, },

View File

@ -2,11 +2,12 @@
* Common part of Checkbox & Radio * Common part of Checkbox & Radio
*/ */
import Icon from '../icon'; import Icon from '../icon';
import { FieldMixin } from './field';
import { ChildrenMixin } from './relation'; import { ChildrenMixin } from './relation';
import { addUnit } from '../utils'; import { addUnit } from '../utils';
export const CheckboxMixin = ({ parent, bem, role }) => ({ export const CheckboxMixin = ({ parent, bem, role }) => ({
mixins: [ChildrenMixin(parent)], mixins: [ChildrenMixin(parent), FieldMixin],
props: { props: {
name: null, name: null,

13
src/mixins/field.js Normal file
View File

@ -0,0 +1,13 @@
export const FieldMixin = {
inject: {
vanField: {
default: null,
},
},
created() {
if (this.vanField) {
this.vanField.children = this;
}
},
};