【问题标题】:Dispatch total of Vue child computed values to parent将 Vue 子计算值的总数发送给父级
【发布时间】:2017-01-07 10:37:20
【问题描述】:

我不知道如何使用 $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() {

        }
    }
})

我有多个“收据”组件实例,因此从组件的计算“总计”函数计算出多个值。如何调度组件实例“总计”函数的值并在父实例中获取我的“总计”

【问题讨论】:

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


    【解决方案1】:

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

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

    eventName 是您的应用预期的事件的名称,并且会在它被调度时选择,数据只是在事件被选择时可供使用的数据。

    在您的应用实例中,您可以定义一个名为“events”的道具来选择事件并对其进行处理。像这样:

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

    像这样,每次调用“yourMethod”(您的组件的方法)时,它都会调度名为“eventName”的事件,而您的应用会选择并处理它。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 2023-03-03
      • 2021-06-29
      • 2021-04-16
      • 2022-09-30
      • 2020-05-02
      • 2020-08-24
      • 1970-01-01
      • 2019-12-04
      相关资源
      最近更新 更多