1

I need to calculate a sum of computed properties that starts with calculateSum string.

I'm not sure how to do that since I can't get their names using this.computed

So my method/attempt is:

getSubTotal(){
    var computed_names = [];
    var computed_names_filtered = computed_names.filter(x => {return x.startsWith('calculateSum')})
    return _.sum(computed_names_filtered.map(x => eval(x+'()'))
}

Do you know how to do that?

2 Answers 2

1

Maybe this can help you to get the list of the computeds:

this.$options.computed
Sign up to request clarification or add additional context in comments.

Comments

1

You could access them dynamically using this['computed_name'] using bracket accessor since the component instance is an object :

var computed_names = Object.keys(this);
var computed_names_filtered = 
computed_names.filter(x => {return x.startsWith('calculateSum')})
 _.sum(computed_names_filtered.map(x => this[x]))

Note that the computed property is called without (), but if you want to call a method you could do this['method_name']()

Example:

// ignore the following two lines, they just disable warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  computed: {
    op1() {
      return 1;
    },
    op2() {
      return 2;
    },
    op3() {
      return 23;
    },
    total() {
      return ['op1', 'op2', 'op3'].map(o => this[o]).reduce((acc, curr) => acc += curr, 0)

    }
  },
   
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  {{total}}
</div>

Comments

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.