Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

computed property set not called in Vue

According to the documentation I should be able to use computed properties as v-model in Vue as long as I define get/set methods, but in my case it doesn't work:

export default{

    template: `
      <form class="add-upload" @submit.prevent="return false">
        <label><input type="checkbox" v-model="options.test" /> test </label>
      </form>
    `,

    computed: {

      options: {

        get(){
          console.log('get');
          return {test: false};
        },

        set(value){
          console.log('set');
        },

      },

    }

}

Apparently set is not called when I check/uncheck the input. But get is called when the component is displayed...

like image 867
Alex Avatar asked Jul 09 '20 16:07

Alex


1 Answers

The very simple explanation here in code. computed properties are dependent on other data/reactive variables. If only when the reactive properties changed their values and if same property used to compute some other computed properties then the computed property would become reactive.

this way we must set values and get in setter and getter methods.

new Vue({
  el: '#app',
  data: {
    message: 'Use computed property on input',
    foo:0,
    isChecked:true
  },
  computed:{
   bar:{
    get: function(){
        return this.foo;
    },
   set: function(val){
     this.foo = val;
    }
   },
   
    check:{
    get: function(){
        return this.isChecked;
    },
   set: function(val){
     this.isChecked = val;
    }
   }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }} Text</p>
  <input type="text" v-model="bar" /> 
  {{bar}}

<br/>
 <p>{{ message }} Checkbox</p>
    <input type="checkbox" v-model="check" /> 
    
    {{check}}
</div>
like image 129
khajaamin Avatar answered Sep 27 '22 20:09

khajaamin