abu abu
abu abu

Reputation: 7028

Call a method of another component

How to call a method of another component ?

Like I have a component named Modal.vue . I have a method like below

<script>
    export default {
        name: 'modal'
        methods: {
            getUsers() {
                //some code here
            }
        },
        created: function () {
            this.getUsers();
        }
    }
</script>

I would like to call that method in another component named Dashboard.vue.

<script>
    export default {
        name: 'dashboard'
        methods: {
            add_adddress () { 
                this.getUsers();  // I would like to access here like this
                //some code here
            }
        },
    }
</script>

I read this question, but how can I use $emit,$on,$broadcast in my current setup ?

Upvotes: 1

Views: 4405

Answers (1)

Omar Tanti
Omar Tanti

Reputation: 1448

In order to use emit one of the components need to call the other (parent and child). Then you emit from the child component to the parent component. For example if Dashboard component uses the Modal component you can emit from the Modal to the Dashboad.

If your components are separate from one another you can make use of Mixins. You can create a mixin UsersMixin.js like the following:

export default {
    methods: {
        getUsers: function () {
            // Put your code here for a common method
        }
    }
}

Then import the mixin in both your components, and you will be able to use its methods:

Modal.vue

<script>
import UsersMixin from './UsersMixin';
export default {
    name: 'modal'
    mixins: [
        UsersMixin
    ],
    created: function () {
        this.getUsers();
    }
}
</script>

Dashboard.vue

<script>
import UsersMixin from './UsersMixin';
export default {
    name: 'dashboard',
    mixins: [
        UsersMixin
    ],
    methods: {
        add_adddress () { 
            this.getUsers();  // I would like to access here like this
            //some code here
        }
    },
}
</script>

Upvotes: 3

Related Questions