Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 in Vue conditional rendering using watcher

I have a drop down (and other inputs) that only need displaying if a checkbox is selected by the user. To keep the UI clean, it's hiding behind a v-if:

<input type="checkbox" id="override" name="override" v-model="override"/>
<div v-if="override">
    <input type="number" name="overridePrice" v-model="overridePrice"/>
    <select class="overrideReason" name="overrideReason" id="overrideReason">
        <option v-for"res in override_reason" :value="res.id">{{ res.text }}</option>
    </select>
</div>

I originally had this set on a watcher for the overridePrice being > 0 which worked:

watch: {
    overridePrice: function(val){
        if(val>0){
            $('.overrideReason').select2();
        }
    }
},

However the reason drop down is required whether the value is 0 or greater, so I figured that changing this to watch on the boolean would be just as easy, but it does not work, the select2 does not initialize properly and I am left with the standard HTML drop down:

watch: {
    override: function(val){
        if (val){
            console.log("This will print");
            $('.overrideReason').select2()'
        }
    }
},

The console log works as expected, however the initialize does not. Is this a bug or am I missing something about Vue watchers/JQuery/Select2?

like image 549
Scott Evans Avatar asked Nov 18 '25 06:11

Scott Evans


1 Answers

This might be .overrideReason is not available at the time watch function is running. You can use $nextTick

watch: {
    override: function(val){
        if (val){
            this.$nextTick(() => {
              console.log("This will print");
              $('.overrideReason').select2()'
            })
        }
    }
},
like image 68
ittus Avatar answered Nov 19 '25 20:11

ittus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!