我对复选框验证有疑问。当我提交时,您会看到第一个元素是必需的,这很好,但是当我选中此复选框并尝试再次提交时,该复选框仍然无效。
该复选框在选中后应变为有效。.
您能帮助修复它吗?
我的小提琴:https://jsfiddle.net/owdamsc4/2/
和摘要:
const FORM_NAME = 'step1Form'
const FORM_RULES = {}
const FORM_MODEL = {
consents: {}
}
validateCheckbox = (rule, value, callback) => {
if (value !== true) {
callback(new Error('Field is required'))
}
callback()
}
const VALIDATORS = {
required: { required: true, message: 'field required', trigger: 'submit' },
checkboxRequired: { type: 'boolean', validator: validateCheckbox, message: 'field required', trigger: 'submit' }
}
var Main = {
data() {
return {
form: FORM_MODEL,
rules: FORM_RULES,
checkAll: false,
formRef: FORM_NAME,
"consentList": [
{
"name": "consent1",
"description": "desc 1",
"url1": null,
"url2": null,
"shouldBeSent": true,
"order": "1",
"required": true
},
{
"name": "consent2",
"description": "desc 2",
"url1": null,
"url2": null,
"shouldBeSent": true,
"order": "10",
"required": false
},
{
"name": "consent3",
"description": "desc 3",
"url1": null,
"url2": null,
"shouldBeSent": true,
"order": "11",
"required": false
}
]
}
},
methods: {
handleCheckAll () {
this.consentList.forEach(consent => {
this.form.consents[consent.name] = this.checkAll
})
},
handleSingleConsent (name) {
this.$forceUpdate()
if (this.form.consents[name]) {
this.form.consents[name] = true
return
}
this.form.consents[name] = false
},
submitStep1 () {
this.$refs[FORM_NAME].validate(valid => {
if (!valid) {
return false
}
console.log('success')
})
}
},
created () {
this.consentList.forEach(field => {
if (field.required) {
Object.assign(this.rules, { [field.name]: [VALIDATORS.checkboxRequired] })
}
this.form.consents[field.name] = false
})
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/element-ui@2.0.5/lib/theme-chalk/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.0.5/lib/index.js"></script>
<div id="app">
<el-form :ref="formRef" :model="form" :rules="rules" @submit.native.prevent="submitStep1">
<div class="inputs">
<el-form-item>
<el-checkbox v-model="checkAll" @change="handleCheckAll">Select all</el-checkbox>
</el-form-item>
<el-form-item v-for="(consent, index) in consentList"
:key="index"
:prop="consent.name">
<div class="checkbox-wrapper">
<el-checkbox :id="consent.name" v-model="form.consents[consent.name]" @change="handleSingleConsent(consent.name)">
<span v-if="consent.required" class="required" style="color: red;">*</span>
<span>{{ consent.description }}</span>
</el-checkbox>
</div>
</el-form-item>
</div>
<el-form-item>
<div class="action-wrapper">
<el-button type="primary" native-type="submit">submit</el-button>
</div>
</el-form-item>
</el-form>
任何帮助将不胜感激。我整天都在浪费它。