Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Yassin Kisrawi Avatar asked Jun 14 '17 15:06

Yassin Kisrawi


People also ask

Can we call a method in computed property?

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.

Can I use props in computed Vue?

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.


1 Answers

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>
like image 189
thanksd Avatar answered Oct 16 '22 13:10

thanksd