我剛開始使用Vue.js並希望使用vee-validator插件,因此我不必重新發明輪子。無論您是否使用VE驗證程序,我相信您的Vue嚮導都會知道如何處理這種情況。將Vue.js中的驗證數據傳遞給插槽
爲了幫助保持我的代碼清潔,以便更新一處更新無處不在我的想法是使一些自定義組件只是很好地風格和包裝HTML輸入。
在這個簡單的例子,我只是有一個的TextInput但想法是遵循相同的格式,但有其他類型的輸入,文字區域,選擇等
我一直在試圖用此示例從工作Vee驗證,但樣本不是很清楚,也不完全是我想要做的。 http://vee-validate.logaretm.com/examples.html#component-example
所以我主要的應用程序是這樣的:
<template>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title pull-left">New Post</h3>
</div>
<div class="panel-body">
<inputWrapper label="My Label" icon="fa-user">
<textInput name="test" placeholder="Edit me"></textInput>
</inputWrapper>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
}
}
</script>
然後我有InputWrapper.vue文件:
<template>
<div class="form-group" v-bind:class="{ 'has-error': errors.has('email') }">
<div class="col-md-12">
<label>{{ label }}</label>
<div class="input-group">
<span class="input-group-addon" v-if="icon"><i class="fa fa-lg " v-bind:class="icon"></i></span>
<slot></slot> <!-- Input element passed from parent -->
</div>
<small class="help-block" v-show="errors.has('email')">
<strong>{{ errors.first('email') }}</strong>
</small>
</div>
</div>
</template>
<script>
export default {
props: ['label', 'icon'],
data(){
return {
}
}
}
</script>
而且我TextInput.vue:
<template>
<input
v-bind:id="name"
v-bind:name="name"
v-bind:placeholder="placeholder"
v-on:keyup="onInput"
class="form-control" />
</template>
<script>
export default {
props: ['name', 'placeholder', 'type'],
data(){
return {
}
},
methods: {
onInput(e) {
const value = e.target.value;
this.$emit('input', value);
}
}
}
</script>
我一直在修補TextInput.vue中的onInput()方法,但我不確定這是我該怎麼做。
注意InputWrapper.vue文件具有'錯誤'errorBag,但它不顯示錯誤。我認爲這是因爲errors.has()和errors.first()不存在於正在驗證的組件中。
如何獲取InputWrapper以顯示來自我的自定義TextInput組件的錯誤?
我已經在主應用程序中添加了v-validate =「'required | email'」到沒有運氣的自定義組件調用,並且在沒有運氣的情況下在TextInput.vue文件中嘗試了它。不幸的是,vee-validator上的文檔並不是一概而論地描述了什麼data-vv-value-path真的是這樣,所以我不知道我應該把它作爲一個值放在那裏。
我願意接受其他現有驗證器的建議,或者選擇做我自己的建議,如果這樣做會讓我的生活更輕鬆。 –