Yassin Kisrawi
Yassin Kisrawi

Reputation: 197

Using Methods inside Computed Properties in vueJs

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.

Upvotes: 20

Views: 40443

Answers (1)

thanksd
thanksd

Reputation: 55664

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>

Upvotes: 34

Related Questions