owlz
owlz

Reputation: 31

How to conditionally set a bootstrap-vue select box value when another select box value selected in vuejs?

I am trying make a conditional select-box. There are 2 select-boxes. When select-box1 1's value changes then the 2nd select-box value automatically need to get selected to a value and it will also be disabled.

So far , i am able to do the conditional select where select-box 1's option changes value in select-box2 but it shows error in vue. Error is--

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"

Also , i can disable the 2nd select-box but when i use dynamic disabled the value doesn't get set.

Question in brief:

  1. 1st selectbox has value-- a)one time payment & b)subscription and
  2. 2nd selectbox has value--a)held & b) Immediate.

Now, if 1st selectbox's subscription is selected then in the 2nd selectbox, it should be set to immediate and also get disabled.

Below is the Code Sandbox link-- https://codesandbox.io/s/conditional-select-forked-h61po?file=/src/components/HelloWorld.vue

If there is a better way of achieving this, then feel free to share ...

Upvotes: 0

Views: 797

Answers (2)

h0p3zZ
h0p3zZ

Reputation: 719

I think the best way is to watch the 2-way-binding (selected) with a watcher.
See: https://v3.vuejs.org/guide/reactivity-computed-watchers.html#watch

And if the value changes you can check if the new value is 'subscription'.

And to select the wante option in the 2nd select you just have to asign the wanted value to the 2-way-binding (selected2). And for disabling set isDisabled to true.

Upvotes: 0

José A. Zapata
José A. Zapata

Reputation: 1297

You don't need a ref, you can change the value of selected2 directly because it's not a prop, but a data field. Remove the reference in your component, like so:

<b-form-select
  v-model="selected2"
  :options="options2"
  :disabled="isDisabled"
></b-form-select>

and change your onChange method to this (you don't need the else block as well):

onChange(event) {
  if (event === "subscription") {
    this.selected2 = "Immediate";
    this.isDisabled = true;
  }
},

Try it. I've tested it and it works.

Upvotes: 0

Related Questions