Vue.component('error', {
template: '#error',
props: ['condition', 'errorMessage']
})
Vue.component('comp', {
template: '#comp',
props: ['errorMessage', 'model'],
})
Vue.component('app', {
template: '#app',
data() {
return {
models: {
nameForm: {
firstName: '',
lastName: '',
__proto__: {
validator: function(value) {
return _(value).every(x => x.length > 2)
}
}
},
otherForm: {
notVeryInterestingField: 'There are words here',
veryImportantField: 0,
__proto__: {
validator: function(value) {
return value.veryImportantField > 20
}
}
},
__proto__: {
validator: function(value) {
return _(value).every(x => x.validator(x))
}
}
}
}
}
})
const vm = new Vue({
el: '#root'
})
.error {
background: orange
}
.alright {
background: mediumaquamarine
}
section > div, pre {
padding: 6px;
}
section {
flex: 1;
}
#root {
display: flex;
flex-direction: column;
}
<script src="https://unpkg.com/vue@2.1.6/dist/vue"></script>
<script src="https://unpkg.com/lodash"></script>
<template id="comp">
<div :class="[model.validator(model) ? 'alright' : 'error']" style="display: flex; border-bottom: 2px solid rgba(0,0,0,0.4)">
<section>
<div v-for="(field, fieldName) in model">
{{_.startCase(fieldName)}}:
<input v-model="model[fieldName]">
<br>
</div>
<error :condition="!model.validator(model)" :error-message="errorMessage"></error>
</section>
<section>
<pre>props: {{$options.propsData}}</pre>
</section>
</div>
</template>
<template id="error">
<div v-if="condition">
{{ errorMessage || 'Oh no! An error!' }}
</div>
</template>
<template id="app">
<div :class="[models.validator(models) ? 'alright' : 'error']">
<comp :model="model" error-message="Mistakes were made." v-for="model in models"></comp>
<pre>data: {{$data}}</pre>
</div>
</template>
<div id="root">
<app></app>
</div>