[Vuejs]-How to share a method between two components in Vue.js?

2👍

there are a couple of ways to achieve this.

One is to use the emit

in the MasterModal.vue component run this.$emit('refreshGrid') in the parent MasterData.Vue component use <ty-master-modal @refreshGrid="RefreshGrid" ...>

if you have a direct parent-child relationship, this is likely the best option

Another way is just to pass a function as a prop to the child component.

<ty-master-modal :onRefreshGrid="RefreshGrid" ...>

and add a prop onRefreshGrid to MasterModal.vue, then you can invoke the function.

Another way, using vuex, is to add a watch to MasterData.Vue and watch a variable in the vuex store ie. actionInvoker. when actionInvoker changes, the action executes. To change the value, set it to 0 and increment or toggle between, or set to random value. The advantage is that you can call this from anywhere.

The problem with this (and the previous) solution is that you have functionality tied to a view/component that shouldn’t be there. I would recommend a third solution, which is to push the functionality into a vuex action, and then you can call it from anywhere. This would require though that you store the selected variable in vuex too, and if you want to have multiple instances of Modal and Master components, a singular store will prohibit that (unless you add support for multiple instances).

👤Daniel

Leave a comment