I am currently developing a Vue component that includes multiple child components. At any given time, only one child component is visible and the user can switch between them only when the currently visible child emits an is-valid
event.
My goal is to maintain decoupling in this setup so that children remain unaware of their parent and communicate solely through event emissions. This also means that the children are oblivious to their location within the parent component.
Therefore, the parent component needs to somehow keep track of which child emitted the event. If the event originated from the correct child (the one currently visible), specific buttons should be activated to allow the user to navigate to the next or previous child.
Here is what I have implemented so far:
HTML
<div id="app">
<template id="m-child">
<div>
<button v-on:click="setstate(true)">Valid</button>
<button v-on:click="setstate(false)">Invalid</button>
</div>
</template>
<template id="m-parent">
<div>
<m-child v-on:newstate="newchildstate"></m-child>
<m-child v-on:newstate="newchildstate"></m-child>
<m-child v-on:newstate="newchildstate"></m-child>
</div>
</template>
<m-parent></m-parent>
</div>
JS
Vue.component('m-child', {
template: '#m-child',
data: function() {
return {};
},
methods: {
setstate: function (valid) {
this.$emit('newstate', valid);
}
}
});
Vue.component('m-parent', {
template: '#m-parent',
methods: {
newchildstate: function (valid) {
console.log('valid:' + valid + ', but where from?');
}
}
});
new Vue({
el: '#app'
});
While I could simply assign an index during the child event binding like this:
<m-child v-on:newstate="newchildstate(0, $event)"></m-child>
<m-child v-on:newstate="newchildstate(1, $event)"></m-child>
<m-child v-on:newstate="newchildstate(2, $event)"></m-child>
Doing so would compromise modularity. My intention is to seamlessly plug in multiple children in the DOM and immediately enable functionality.
After reviewing the Vue events API, it appears that there is no straightforward method to identify the event source.