user1692333
user1692333

Reputation: 2597

How to properly use childs component methods in parent in VUE?

I have ImageUpload.vue component which is simple Bootstrap modal with few methods.

I'm wondering what is the best way to use one of those methods? Something like this:

const app = new Vue({
    components: {
        'component-image-upload': require('./components/ImageUpload.vue'),
    },
    el: '#app',
    data() {
        return {
            images: [],
            pagination: {
                previous: null,
                next: null
            }
        }
    },
    methods: {
        createImage: function(page) {
            this['component-image-upload'].load(image)
        }
    }
});

The idea is simply to reuse that model to edit existing image data.

Upvotes: 0

Views: 221

Answers (2)

Jayesh Dhandha
Jayesh Dhandha

Reputation: 2119

The best way to do this is Custom Event

You can trigger any event from your component to the #root element which you have loaded in vue instance.

$emit('event-name') can be used to trigger the event!!

I hope this helps :)

Upvotes: 0

Philip Feldmann
Philip Feldmann

Reputation: 8365

When you find yourself calling methods from another (child) component you should rethink your architecture. Vue components are reusable parts you can use to assemble a view, they are not meant to share javascript logic across your application. If you want to do that you're better off writing a module and importing its functions in your parent Vue file. The way you "communicate" with your child components properly is by prop-bindings, which contain data and can re-trigger the render loop of your child component. Communicating from the child to the parent is done by dispatching events. You never want to share logic between the two.

Regardless here's how you can do it anyway:

You have to have an element of your child component in the parent's template, otherwise it wont be mounted and its methods can't be accessed:

<component-image-upload ref="image" />

Then you can call any method on that component by using its ref:

createImage (page) {
  this.$refs.image.myMethod('this is how you call it from parent')
}

Upvotes: 2

Related Questions