I am trying to create dynamic Vue components that keep track of their own error state. I need the validation to take place on the parent component, and the parent validation method should update the child component error state. At this stage I cannot guess how many child components will be generated, making it difficult to keep track of via props. The number of child components that will be rendered is dynamically determined via an API call.
The only way I've found to accomplish this so far is to pass the component instance to the parent via a function parameter and updating the data attribute in directly in the parent component.
My question is this - is there a better way to do this than passing the component instance as a function parameter?
HTML
<div id="app">
<number-only v-for="n in 8"
v-on:update="checkNumber"></number-only>
</div>
CSS
input {
display: block;
margin: 5px;
}
input.error {
border: 1px solid #ff0000;
background-color:
}
JavaScript
Vue.component('numberOnly', {
template: `<input type="text"
:class="{error: hasError}"
@keyup="update($event.target.value)"
/>`
,
data() {
return {
hasError: false
}
},
methods: {
update(val){
this.$emit('update', {
value: val,
instance: this
});
}
}
});
new Vue({
el: '#app',
components: ['numberOnly'],
methods: {
checkNumber(args){
if(isNaN(args.value)){
args.instance.hasError = true;
return;
}
args.instance.hasError = false;
}
}
});
Here is a working Codepen example: https://codepen.io/martiensk/pen/wroOLN