I'm trying to call a method inside of a computed property. My code is more complicated, but calling the method doesn't seem to even work in this simple example:
new Vue({
el: '#vue-instance',
data: {
x: 1
},
methods: {
augmented: function(variable) {
return (2 * variable);
},
},
computed: {
doubleX: function() {
return augmented(this.x);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="vue-instance">
<input type="number" v-model="x"> result: {{ doubleX }}
</div>
As you can see by running the snippet, the value of doubleX
is not getting rendered.
Computed Caching vs MethodsInstead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies.
You can put a watcher on any reactive property. This includes computed props, props, as well as data that is specified inside of data() on your Vue component. They're really useful for creating side effects — things that don't update your application's state immediately.
You need to reference your component's methods via this
:
var vm = new Vue({
el: '#vue-instance',
data: {
x: 1
},
methods: {
augmented: function(variable) {
return (2 * variable);
},
},
computed: {
doubleX: function() {
return this.augmented(this.x);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="vue-instance">
<input type="number" v-model="x"> result: {{ doubleX }}
</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