SPQRInc
SPQRInc

Reputation: 188

Select box does not update v-model

I got a little problem that I'm unable to solve. I created a select box like this https://codepen.io/spqrinc/pen/wvaqrPj

<div id="app">
  Selected value: {{item.picked}}
  <hr />
<select v-model="item.picked">
  <option v-for="(item, index) in item.values" :value="item.value" :key="index">{{item.value}} - {{item.title}}</option>
</select>
</div>

This is working (as you can see on the example).

Now I included vue-router and added this:

  beforeRouteEnter (to, _from, next) {
            let querypath = `/path/to/api`;

            next (vm => {
                vm.$wait.start ('loading');
                axios
                .get (querypath).then ((resp) => {
                    vm.item = resp.data.data;
                    vm.item.picked = 1;
                    vm.$wait.end ('loading');
                });
            });
        },

Now the first value is automatically selected. But if I select an other value, the v-model is not updated. Selected value: always shows 1.

Why is this the case?

Thanks for your help.

Upvotes: 0

Views: 1315

Answers (1)

seantunwin
seantunwin

Reputation: 1768

item.picked is not reactive in Selected value: {{item.picked}} so it only reads the initial value on mount.

To clarify one of your points, the v-model is being updated, but the display is not.

To fix this use a computed property which returns item.picked.

e.g.

  • Refactor Selected value: {{item.picked}} to Selected value: {{pickedItem}}
  • Add a computed property of pickedItem
computed: {
    pickedItem() {
      return this.item.picked;
    }
  }

Upvotes: 1

Related Questions