Sometimes, we want to bind method result to v-model with Vue.js.
In this article, we’ll look at how to bind method result to v-model with Vue.js.
How to bind method result to v-model with Vue.js?
To bind method result to v-model with Vue.js, we can put the logic in a computed property.
For instance, we write
<template>
<div id="app">
<input v-model="doubleValue" />
</div>
</template>
<script>
//...
export default {
//...
data() {
return { value: 5 };
},
computed: {
doubleValue: {
get() {
return this.value * 2;
},
set(newVal) {
this.value = newVal / 2;
},
},
},
//...
};
</script>
to add the doubleValue
computed property which has a getter and a setter.
In the get
getter, we return this.value
multiplied by 2.
And in the set
setter, we set this.value
to newVal
divided by 2.
And then we use that with v-model
to bind doubleValue
to the input value.
Conclusion
To bind method result to v-model with Vue.js, we can put the logic in a computed property.