1

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 ?

abu abu
  • 6,599
  • 19
  • 74
  • 131
  • 1
    Possible duplicate of [Call a Vue JS component method from outside the component](https://stackoverflow.com/questions/33682651/call-a-vue-js-component-method-from-outside-the-component) – sliptype Mar 27 '18 at 15:45
  • In order to use the `emit` the components need to be called from each other for e.g. dashboard component uses the modal component, and then you emit from the modal to the dahsboard. If the components are separate I would suggest that you create a mixin which you can import in any component and have all its methods available. – Omar Tanti Mar 27 '18 at 17:59

1 Answers1

3

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>
Omar Tanti
  • 1,368
  • 1
  • 14
  • 29