A
A
Anton89892018-08-08 10:05:49
Vue.js
Anton8989, 2018-08-08 10:05:49

How to get dynamic sum output from two components?

There is the following code, where there are two components, please tell me how you can display the total amount of these two components when the checkboxes are pressed (this html needs to remain the same, I will need it for layout:

<div id="app">
  SUM: {{ sum }}
<checkbox-counter1></checkbox-counter1>
<checkbox-counter2></checkbox-counter2>
</div>
)
code:
<div id="app">

    SUM: {{ sum }}


<checkbox-counter1></checkbox-counter1>
<checkbox-counter2></checkbox-counter2>


</div>


<script>

Vue.component('checkbox-counter1', {
  data: function () {
    return {
      items:[
        { value: [3.99, 1], checked: false },
        { value: [4, 2], checked: false },
        { value: [7, 3], checked: false },
      ],
      checkAll: false,
    }
  },
   computed: {
     total() {
      const val1 = this.items.reduce((acc, n) => acc + n.value[0] * n.checked, 0);
      this.$emit('change', val1);
      return val1;
    },
    day(){
        return this.items.reduce((acc, n) => acc + n.value[1] * n.checked, 0);
    }
    },
        watch: {
        checkAll(val) {
        this.items.forEach(n => n.checked = val);
        },
    },
  template: '<div><input v-for="n in items" v-model="n.checked" type="checkbox"> <div>{{ total }}</div> <div>{{ day }}</div> <div><input type="checkbox" v-model="checkAll"></div></div'
})



Vue.component('checkbox-counter2', {
  data: function () {
    return {
      items:[
        { value: [1, 1], checked: false },
        { value: [1, 1], checked: false },
        { value: [1,1], checked: false },
      ],
      checkAll: false,
    }
  },
   computed: {
     total() {
      const val2 = this.items.reduce((acc, n) => acc + n.value[0] * n.checked, 0);
      this.$emit('change', val2);
      return val2;
    },
    day(){
        return this.items.reduce((acc, n) => acc + n.value[1] * n.checked, 0);
    }
    },
        watch: {
        checkAll(val) {
        this.items.forEach(n => n.checked = val);
        },
    },
  template: '<div><input v-for="n in items" v-model="n.checked" type="checkbox"> <div>{{ total }}</div> <div>{{ day }}</div> <div><input type="checkbox" v-model="checkAll"></div></div'
})





new Vue({
  el: '#app',
  data: {
   
  },
  computed: {
    sum() {
       

    }
  }
});

5b6a9647e6354006619026.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-08
@Anton8989

What is the difference between your components? In data? This means that the component must be one and accept parameters. Well, in the rest - you asked a similar question yesterday .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question