In my project, I have implemented a cascading select feature where the options in the second dropdown are dependent on the value selected in the first dropdown. This is achieved by using a computed property based on the first select to populate the options in the second select. While this setup works well for the most part, I am encountering an issue.
The problem arises when I choose an option in the second select (which updates the bound variable value via v-model) and then proceed to change the value in the first select. As a result, the options in the second select are updated accordingly, but visually it appears as though I have no selection in the second dropdown. However, the bound variable retains its previously selected value. I suspect that this occurs because updating the options for the second select does not trigger an input or change event, causing v-model to not respond. Although I could address this with a watcher, I was hoping to find a more elegant solution.
For a coded example, you can check out this link: https://codepen.io/Slotheroo/pen/ajwNKO/
JS/Vue:
new Vue({
el: '#app',
data: {
selectedFruit: null,
selectedVariety: null,
fruits: {
"apples": [
{
name: "honeycrisp",
madeBy: "applebees",
},
{
name: "macintosh",
madeBy: "the steves",
},
{
name: "gala",
madeBy: "ac/dc",
},
{
name: "pink lady",
madeBy: "Alecia Beth Moore",
},
],
"pears": [
{
name: "d'anjou",
madeBy: "Maya D'Anjoulou",
},
{
name: "bartlett",
madeBy: "Anton Yelchin",
}
],
},
},
computed: {
fruitVarieties: function() {
return this.fruits[this.selectedFruit]
}
},
});
HTML:
<div id="app">
<div>
<select v-model="selectedFruit">
<option value=""></option>
<option v-for="fruitName in Object.keys(fruits)" :value ="fruitName">{{fruitName}}</option>
</select>
</div>
<select v-model="selectedVariety">
<option value=""></option>
<option v-for="fruitVariety in fruitVarieties" :value="fruitVariety">{{ fruitVariety.name }}</option>
</select>
<div>
</div>
<p>Selected variety: {{ selectedVariety }}</p>
</div>
Steps to reproduce:
- Select 'apples' from the first select dropdown
- Choose 'honeycrisp' from the second select dropdown
- Now, pick 'pears' or leave it blank in the first select dropdown
Expected outcome:
The selectedVariety should revert back to null
Actual outcome:
The selectedVariety remains as honeycrisp