Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when v-model is null, set checkbox value to be false in Vue.js

Tags:

vuejs2

In the following vue.js example, if the value of myBool is null, checkbox doesn't return N.

<input v-model="myBool" true-value="Y" false-value="N" type="checkbox">  

However, if I set myBool to false, checkbox returns N. How can I get the value N even though myBool is null? I don't want to manually check the return value of the checkbox, then add a logic to make it false. Is there any better way to get the N value when myBool is null?

like image 819
Circuit Breaker Avatar asked Nov 17 '25 22:11

Circuit Breaker


1 Answers

I haven't tried this out, but maybe set v-model to a Computed Setter

computed: {
  myBoolComputed: {
    // getter
    get: function () {
      return this.myBool ? true : false
    },
    // setter
    set: function (newValue) {
      this.myBool = newValue
      // or if preferred to stay strictly Boolean
      // this.myBool = (newValue === 'Y')
    }
  }
}

The template

<input v-model="myBoolComputed" true-value="Y" false-value="N" type="checkbox">
like image 56
Richard Matsen Avatar answered Nov 19 '25 12:11

Richard Matsen