0

I have two linked selects that allows the user to select the first option (which is kind of "what you already have") and that option is then excluded from the other select (you can think of it as "what you want").

Here is my current code:

var linkedSelects = new Vue({
  el: '#linked-selects',
  data: {
    opt1: null,
    opt2: null,
    options: ['a', 'b', 'c', 'd']
  },
  computed: {
    allOptions() {
      const allOptions = [...this.options];
      
      allOptions.push('other');
      
      return allOptions;
    },
    remainingOptions() {
      const remainingOptions = [...this.options];
      
      remainingOptions.push('any');
      
      const opt1Index = remainingOptions.indexOf(this.opt1);
      
      if (-1 < opt1Index)
        remainingOptions.splice(opt1Index, 1);
        
      return remainingOptions;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="linked-selects">
  <div>
  Choose what to exclude:
    <select v-model="opt1">
      <option
        v-for="opt in allOptions" 
        :value="opt" 
        :key="opt" >
          {{opt}}
      </option>
    </select>
  </div>

  <div>
    Select out of the remaining:
    <select v-model="opt2">
      <option
        v-for="opt in remainingOptions" 
        :value="opt" 
        :key="opt" >
          {{opt}}
      </option>
    </select>
  </div>
  
  <div>Value 1: {{opt1}}</div>
  <div>Value 2: {{opt2}}</div>
</div>

A problem arises when the following sequence of actions is made:

  1. User selects an option (say a) in the second select.
  2. User selects the same option (a) in the first select.

When this is done, the option a is removed from the second select but the value of opt2 remains equal to a. How can I make Vue change it to null at that situation?

The particular need to solve this is because I am using Buefy and leaving opt2 to nonexistant option makes the select appear empty instead of displaying the placeholder. To see a placeholder the option must be changed to null.

1 Answer 1

1

You can add a watcher on opt1. If its value is the same as opt2, reset opt2 to null:

watch: {
  opt1(value) {
    this.opt2 = value === this.opt2 && null
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I had somehow missed this simple idea and lost myself in complicated thoughts about checking the array changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.