RoboKozo
RoboKozo

Reputation: 5062

How to get around vuetify's v-select internal state

I'm trying to prevent a value from being 'selected' when using vuetify's v-select component.

Given:

<v-checkbox
    v-model="allowChanges"
></v-checkbox>
<v-select
    v-model="twoWayComputed"
    :items="items"
></v-select>

new Vue({
  el: '#app',
  data: () => ({
    selected: "Foo",
    allowChanges: false,
    items: ['Foo', 'Bar', 'Fizz', 'Buzz']
  }),
  computed: {
    twoWayComputed: {
      get(){
        return this.selected
      },
      set(val){
        if (this.allowChanges){
          console.log("updating")
          this.selected = val
        }
      }
    }
  }
})

Codepen: https://codepen.io/anon/pen/mYNVKN?editors=1011

When another value is selected, the components selected value is not being updated. However v-select still shows the new selected value.

I even tried all kinds of "tricks" like

  set(val){
    if (this.allowChanges){
      console.log("updating")
      this.selected = val
    } else {
      this.selected = this.selected
    }

but no luck.

I believe v-select is maintaining its own internal selected value.

Upvotes: 3

Views: 4665

Answers (2)

Kael Watts-Deuchar
Kael Watts-Deuchar

Reputation: 4481

This does nothing:

this.selected = this.selected

You have to set the value, wait for vue to update the props, then set it back again:

const oldVal = this.selected
this.selected = val
this.$nextTick(() => {
  this.selected = oldVal
})

Codepen

Upvotes: 2

Adam Orłowski
Adam Orłowski

Reputation: 4464

I made it using slot-scope look:

<v-select
  v-model="twoWayComputed"
  :items="items"
  label="scoped"
>
  <template slot="selection" slot-scope="data">
    {{ selected }}
  </template>
  <template slot="item" slot-scope="data">
    {{ data.item }}
  </template>
</v-select>

  data: () => ({
    selected: "Foo",
    allowChanges: false,
    items: ['Foo', 'Bar', 'Fizz', 'Buzz']
  }),
  computed: {
    twoWayComputed: {
      get(){
        return this.selected
      },
      set(val) {
        if (this.allowChanges) {
          console.log("updating")
          this.selected = val
        } 
      }
    }
  }

check-out-my-codepen

Upvotes: 3

Related Questions