I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle:
https://jsfiddle.net/ywaug7ft/
Here's the HTML snippet:
<div id="app">
<h5>Select a gender</h5>
<select v-model="gender">
<option disabled="disabled" value>Select...</option>
<option value="1">Male</option>
<option value="2">Female</option>
<option value="3">Couple</option>
</select>
<div></div>
<detail-component v-for="(detail, index) in details" :data="detail" :index="index"></detail-component>
{{details}}
</div>
<template id="details">
<div>
<h4><span v-if="item.gender == 3 && index == 0">Her</span><span
v-else-if="item.gender == 3 && index == 1">His</span><span v-else>Your</span> Health Details</h4>
<div>Index: {{index}}</div>
<div>Gender: {{item.gender}}</div>
</div>
</template>
And the Vue section:
Vue.component('detail-component', {
template: '#details',
props: ['data', 'index'],
data() {
return {
item: {
gender: this.data.gender
}
}
}
});
var app = new Vue({
el: '#app',
data: {
gender: '',
details: [],
options: {
gender: {
"1": "Single Female",
"2": "Single Male",
"3": "Couple"
}
}
},
watch: {
gender: function(val) {
this.details = [];
if (val == 1) {
this.details.push({gender: 1});
} else if (val == 2) {
this.details.push({gender: 2});
} else if (val == 3) {
this.details.push({gender: 3}, {gender: 3});
}
}
}
});
The issue arises when selecting female
or male
, the vue component should display Your Details
. If couple
is selected, it should show Her Details
and His Details
. However, the first index does not update to Her
but remains as Your
.
Please check out the jsfiddle link provided to see the exact problem.
I'm trying to figure out what mistake I might be making here. My understanding was that using a watcher would make the component reactive. Any insights into my error would be greatly appreciated.