Reputation: 11
Ok so i am working on some code which allows a user to change the store they belong to. I am using a tag and in it i have a v-model. in the tag i use a for loop to give the stores the user can choose from.
Here is my code:
<div v-if="contestant.stores.length > 1" class="mt-10 col-sm-10">
<select class="form-control" v-model="riot_account_store" v-on:change="onChangeStore()">
<option v-for="store in contestant.stores" :key="store.objectId" :value="store.objectId">{{ store.name }}</option>
</select>
</div>
All i want now is to add an "unchanged" default value to appear FIRST before all the choices. Basically a simple <option>unchanged</option>
nothing special. Problem is when i add any other option it is simply skipped. It does still appear if i hit the select and it appears above the first choice from the loop. So it is being compiled just not "chosen" as a first value. No idea what the problem is. Any thoughts?
Upvotes: 0
Views: 5852
Reputation: 7018
Your option needs a value. That's it:
const app = new Vue({
el: '#app',
data: {
riot_account_store: null,
stores: [
{ objectId: 12, name: 'Foo' },
{ objectId: 13, name: 'Bam' },
{ objectId: 14, name: 'Baz' },
],
},
methods: {
onChangeStore() {
console.log(this.riot_account_store);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-if="stores.length > 1" class="mt-10 col-sm-10">
<p>Selected: {{ riot_account_store }}</p>
<select class="form-control" v-model="riot_account_store" v-on:change="onChangeStore()">
<option :value="null">unselect</option>
<option v-for="store in stores" :key="store.objectId" :value="store.objectId">{{ store.name }}</option>
</select>
</div>
</div>
Upvotes: 2
Reputation: 532
You will have to store the 'initial' selection somewhere, for example in the data-block:
data() {
return {
initialSelection: { objectId: 10, name: 'Generic store name' } // you can set this property for example in the mounted() lifecycle-hook
}
Then edit your -Tag to:
<option v-for="store in contestant.stores" :key="store.objectId" :value="store.objectId">{{ store.objectId === initialSelection.objectId ? 'unchanged' : store.name }}</option>
Upvotes: 0
Reputation: 14171
Add your default option
, assign a value
that is not taken and init your v-model
with value. Vue binding will take care of the rest.
<div v-if="contestant.stores.length > 1" class="mt-10 col-sm-10">
<select class="form-control" v-model="riot_account_store" v-on:change="onChangeStore()">
<option value="not_taken_id">default</option>
<option v-for="store in contestant.stores" :key="store.objectId" :value="store.objectId">{{ store.name }}</option>
</select>
</div>
date () {
return {
riot_account_store: 'not_taken_id'
}
}
Upvotes: 0