I couldn’t find a guideline to implement this. How would you add data to errors bag from parent component and listen to the particular error from child components to show something conditionally?
I’ve added the error to the errors bag from the parent
component like the following:
export default { mounted () { this.$validator.errors.add('critical', 'Unable to connect', 'network') } }
Now, from the child
component, I’d like to show something conditionally depending on the error bag whether there is an error or not. I’ve added my child component the following:
<a class="navbar-item" v-if="!errors.has('critical')">Hello World</a>
The errors.has('critical')
return false
as VeeValidate returns a new instance for each component. So, how do I go about transfer the same errors bag from parent component to child?
Advertisement
Answer
I have no experience with VeeValidate, however, I guess the Vue way should work just fine no matter what you’re using.
There is also probably another way to do it with your library though. Anyway, I’d do it that way:
Step 1
Emit your event from your parent component’s method:
let payload = { message: 'Unable to connect', type: 'network' }; this.$emit('error', payload);
#Step 2
In your child component, or any component:
let self = this; $on('error', (payload) => { self.error = payload; });
#Step 3
You can now access it from the template side in your other component:
<div class="alert alert-danger" v-if="error.type == 'critical'" v-text="error.message"></div>
This is just an example. It’s ES6, feel free to translate in other version.
The doc you’re looking for is here: https://v2.vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events