Mvvm 将Vue子计算值的总数分派给父级
我不知道如何使用$dispatch方法将数据从Vue子级发送到Vue父级。我有一个具有多个实例的组件,如下所示:Mvvm 将Vue子计算值的总数分派给父级,mvvm,components,vue.js,dispatch,vue-component,Mvvm,Components,Vue.js,Dispatch,Vue Component,我不知道如何使用$dispatch方法将数据从Vue子级发送到Vue父级。我有一个具有多个实例的组件,如下所示: Vue.component('receipt', { template: '#receipt-template', data: function() { return { tip: '' }; }, methods: { addSale: function() {
Vue.component('receipt', {
template: '#receipt-template',
data: function() {
return {
tip: ''
};
},
methods: {
addSale: function() {
this.sales.push(
{amount: 1, desc: '', price: 0.00}
);
},
removeSale: function(index) {
this.sales.splice(index, 1)
}
},
computed: {
subtotal: function() {
var result = 0;
this.sales.forEach(function (sale) {
return result += +sale.price;
});
var subtotal = Math.round(100 * result) / 100;
return subtotal.toFixed(2);
},
tax: function() {
var tax = this.subtotal * .08;
return tax.toFixed(2);
},
total: function() {
var total = Number(this.subtotal) + Number(this.tax) + Number(this.tip);
return total.toFixed(2);
this.$dispatch(this.total);
}
},
props: [ 'header', 'date', 'sales' ]
})
我的Vue实例如下所示:
var vm = new Vue({
el: '#content',
data: {
sales1: [
{amount: 1, desc: "Dante's Inferno", price: 13.99},
{amount: 1, desc: "Espresso", price: 5.25},
{amount: 1, desc: "The Sun Also Rises", price: 11.99},
{amount: 1, desc: "Spanish Coffee", price: 1.99}
],
sales2: [
{amount: 1, desc: "Huckleberry Finn", price: 14.95},
{amount: 1, desc: "Americano", price: 2.29},
{amount: 1, desc: "Pride & Prejudice", price: 12.95},
{amount: 1, desc: "Black Tea Latte", price: 4.25},
{amount: 1, desc: "Scone", price: 3.25}
],
company: 'Between The Covers & Grinders Cafe'
},
computed: {
grand: function() {
}
}
})
我有多个“收据”组件的实例,因此从组件的计算“总计”函数计算多个值。如何分派组件实例“total”函数的值并在父实例中获取我的“grandtotal”您必须在组件中创建一个“分派”事件的方法,如下所示:
methods: {
yourMethodName: function(){
this.$dispatch('eventName', data);
}
}
eventName是您的应用程序预期的事件名称,在发送时将拾取该事件,数据只是拾取事件时可用的数据
在你的应用程序实例中,你可以定义一个名为“事件”的道具,选择事件并对其进行处理。像这样:
events: {
'eventName': function(data){
//do something with it
}
}
像这样,每次调用“yourMethod”(组件的方法)时,它都会发送名为“eventName”的事件,而应用程序将拾取并处理该事件
希望有帮助