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...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With