Good day. There are several components in which there is an array of data (name, price). All of them are connected through the main component. How can I get the sum of the prices of all selected items from all components?

Closed due to the fact that the question is not clear to the participants of AK , Vadim Ovchinnikov , fori1ton , rjhdby , Denis Bubnov January 24, '17 at 6:42 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    How, how .. For each component, take the sum of all prices, then sum up over all components. Add your sample code, otherwise it is difficult to advise something other than such trivial things. - AK

1 answer 1

At the expense of interaction in Vue.js, the position is simple: Descendants send events, ancestors send data "down."
Well, something like this:

Vue.component('Price', { template: ` <div class="priceWrapper"> <label> <input type="checkbox" v-model="state" @click="handler" /> Цена: $\{{price}} </label> </div>`, data: function(){ return { state: false, price: Math.floor(Math.random() * (500 - 1 + 1)) + 1 } }, methods: { handler: function(){ // Изменение чекбокса вызывает эмит данных для предка this.$parent.$emit('change', this.price, this.state); } } }); new Vue({ el: '#example', data: { total: 0 }, created(){ // Слушаем события от потомков // Получаем цену и состояние чекбокса this.$on('change', function(price, state){ this.total = state ? this.total + price : this.total - price; }); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script> <div id="example"> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <Price></Price> <span>Общая цена: <strong>${{total}}</strong></span> </div>