How can I share a method between components in Vue.js?

前端 未结 4 1500
野趣味
野趣味 2020-12-13 03:55

Check out this simple shopping cart demo:

http://plnkr.co/edit/CHt2iNSRJAJ6OWs7xmiP?p=preview

A user can pick a veggie and a fruit, and it will be added into

4条回答
  •  臣服心动
    2020-12-13 04:32

    You can put the method in your root Vue instance and then dispatch an event from the child instance when a veggie is selected, or when a fruit is selected. Events look for a handler on their parent component, and if they don't find an event handler they keep going up the chain until they do. So on your root instance:

    events: {
        'choose-fruit':function(fruit){
    
            //handle the choosing of fruit
    
        }
    }
    

    Then on the child instance:

    selectFruit: function(product){
    
        this.$dispatch('choose-fruit', product);
    
    }
    

提交回复
热议问题