我不能使用vee-validate支持制作自定义复选框组件 . 我是Vue的新手 . 在我的应用程序中必须要求复选框 . 但它不起作用 . 我阅读了很多关于vee-validate和自定义输入的文章,但所有的例子都基于简单的自定义文本输入 .
这个时候我的代码下面 .
Parent component :
<!-- Custom text input. Vee-validate works nice. -->
<input-text
name="email"
placeholder="Please, enter email"
label="Email"
:required="true"
:type="'email'"
:value.sync="shareholder.fields.email"
v-validate.initial="'required|email'"
data-vv-delay="500"
:className="{'error': isShowError('email')}"
:disabled="isDisabled"
/>
<!-- Custom checkbox input. Vee-validate doesn't work. -->
<checkbox2
name="consent"
v-if="consent"
class="consent"
:required="true"
:disabled="isDisabled"
:className="{'error': errors.first('consent')}"
:error="errors.first('consent')"
v-model="consentStatus"
v-validate.initial="'required'"
>
{{consent.text}}<br><a :href="consent.link" target="_blank">{{consent.linkText}}</a>
</checkbox2>
{{ errors.first('consent') }}
档案 check-box.vue :
<template>
<div class="checkbox"
:class="{ active: !!value }"
>
<label class="control">
<input
@change="handleChange"
type="checkbox"
:name="name"
:checked="value"
/>
<span class="icon-checkbox"></span>
</label>
<div class="label">
<slot />
</div>
</div>
</template>
<script src="./check-box.js"></script>
<style lang="stylus" src="./check-box.styl" scoped></style>
档案 check-box.js :
export default {
name: 'checkbox2',
inject: [ '$validator', ],
// In one of articles I read I must bind event and value
// with check box like below. But it seems it doesn't work too.
model: {
event: 'input',
value: 'checked',
},
props: {
value: {
type: Boolean,
default: false,
},
error: {
type: String,
},
name: String,
disabled: Boolean,
className: Object,
required: Boolean,
},
data: function() {
return {
checked: false,
}
},
methods: {
handleChange() {
if (!this.disabled) {
this.checked = !this.value
// If I emit 'change' instead of 'input',
// checkbox component works wrong.
this.$emit('input', this.checked)
}
},
},
created() {
this.checked = this.value
this.$validator = this.$parent.$validator
},
}
1 回答
用户必须选中我们的复选框才能使表格有效 .
首先,在vee-valid
'required'
中Boolean
是true
,当它不等于null
时 . 即如果consentStatus = null
,则默认情况下下面的复选框无效(根据我的需要) .但在这种情况下, both 可能的值(
true
和false
)使此组件有效 .变体1
默认情况下,规则
v-validate.initial="{ is: true }"
不适用于 vee-validate 2.1.0-beta-9 及以下 . 所以我们需要 crutch .在导入后的父组件js文件中,我们应该定义自定义验证器规则 .
父vue文件的代码:
变体2
我们将值作为数字进行比较 . 家长vue代码:
档案 check-box.vue :
档案 check-box.js :