20

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.

1 Answer 1

34

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>

Sign up to request clarification or add additional context in comments.

5 Comments

Great Thanks for you sir :) Still have a question, is it possible to call a function directly into the html ? meaning can i do something like result: {{ augmented(2) }}
Yep just like that {{ augmented(2) }}
@SanjaysinhZala If you're saying that you have a computed property called augmented and you want to reference the value of that property in your template, then you would just write {{ augmented }}
@thanksd i am saying that if doubleX and augmented both are in computed then how augmented property will call from doubleX.
@SanjaysinhZala Within a computed, you can reference other computed just like regular properties (i.e. this.augmented or this.doubleX). See the docs: vuejs.org/v2/guide/computed.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.