[Vuejs]-Avoid redundant calls to Vue component when needing to return different data from one component

0👍

You could make these computed properties instead. That way, the function for each individual property will only get called when that property is accessed:

const numbers = Vue.component('numbers', {
  props: ['table'],
  computed: {
    first() {
      console.log('`first` computed');
      return this.table[0][1];
    },
    last() {
      console.log('`last` computed');
      return this.table[this.table.length - 1][1];
    },
    sum() {
      console.log('`sum` computed');
      return this.table.reduce((n, i) => n + i[1], 0);
    }
  }
})

Vue.component('sumvalue', numbers.extend({
  template: '<span>{{sum}}</span>'
}))

Vue.component('firstvalue', numbers.extend({
  template: '<span>{{first}}</span>'
}))

Vue.component('lastvalue', numbers.extend({
  template: '<span>{{last}}</span>'
}))

new Vue ({
  el: '#app',
  data() {
    return {
      datafromflask: [ [null, 7], [null, 5], [null, 3], [null, 3], [null, 8], [null, 2] ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
  <p>sum: <sumvalue :table='datafromflask'></sumvalue></p>
  <ul>
    <li><p>first: <firstvalue :table='datafromflask'></firstvalue></p></li>
    <li><p>last: <lastvalue :table='datafromflask'></lastvalue></p></li>
  </ul>
</div>

Leave a comment