Vuejs: how to create a condition for a v-model?

Asked

Viewed 674 times

4

The problem is, I have a switch made with label and input checkbox and it has a default value that comes from date of my instance of Vue.

var app = new Vue({
    el: '#app',
    data: {
        slcModalidad: 0,
        chkPosNet: true,
    },

<label for="chkAllowPosNet" class="label-chk-allow">
     <input type="checkbox" id="chkAllowPosNet" name="chkAllowPosNet" v-model="chkPosNet">
          <div class="allow-text"></div>
          <div class="allow-toggle"></div>
</label>

However I need the default value of the variable chkPosNet pass a condition to determine whether it is true or false, which in my example would be if the slcModalidad is greater than 2. What would be the best way to do this?

I thought I’d leave the chkPosNet as null and create a method for checking, but I got confused whether I do in methods, computed, Mounted.... or whether I can do a v-if for v-model.

2 answers

1

Your Watcher works, but I find it more appropriate to transform chkPosNet in a computed property:

var app = new Vue({
    el: '#app',
    data: {
        slcModalidad: 0
    },
    computed: {
        chkPosNet: function() {
            return this.slcModalidad <= 1;
        }
    },
    ....
  • can tell me the advantage of using computed in place of Watcher?

  • It is possible (I am not sure) that the Watcher weighs more. Computed properties are the feature that Vue offers to do exactly what you want, while Watcher is a more generic thing.

0


I solved my problem like this, I created a Watcher to keep watching the variable slcModalidad and made a Vertification inside it:

watch: {
            slcModalidad: function(){
                if(this.slcModalidad > 1){
                    this.chkPosNet = false
                }
            },
        },

Browser other questions tagged

You are not signed in. Login or sign up in order to post.