将Vue子计算值的总计调度发送给父级

时间:2016-08-31 01:33:56

标签: mvvm components vue.js dispatch vue-component

我无法弄清楚如何使用$ dispatch方法将数据从Vue子节点发送到Vue父节点。我有一个包含多个实例的组件,如下所示:

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'功能,让我的祖父母'在父实例中

1 个答案:

答案 0 :(得分:2)

您必须在组件中创建一个“调度”事件的方法,如下所示:

methods: {
        yourMethodName: function(){
            this.$dispatch('eventName', data);
        }
    }

eventName是您的应用所期望的事件的名称,并将在调度时选择,数据只是在挑选事件时可用的数据。

在您的应用实例中,您只需定义一个名为'events'的道具,即可选择该事件并对其执行操作。像这样:

events: {
        'eventName': function(data){
            //do something with it
        }
    }

像这样,每当调用'yourMethod'(你的组件的方法)时,它将调度名为'eventName'的事件,你的应用程序将选择并处理它。

希望有所帮助!