Categories
Vue Answers

How to Share a Method Between Components in Vue?

Spread the love

Sometimes, we want to share methods between components in our Vue project.

In this article, we’ll look at how to share methods between components in our Vue project.

Share a Method Between Components in Vue

To share a method between components in Vue, we can create a module that exports the method.

For instance, we can write:

src/shared.js

export default {
  bar() {
    alert("bar")
  }
}

Then we can use it in our component by writing:

src/App.js

<template>...</template>

<script>
import shared from './shared'

export default {
  created() {
    shared.bar();
  }
}
</script>

We imported the shared module and called the bar method inside it.

Alternatively, we can create a mixin, which is a piece of code that can be merged into our component.

For instance, we can write:

const cartMixin = {
  methods: {
    addToCart(product) {
      this.cart.push(product);
    }
  }
};

Then we can use it in our component by writing:

const Store = Vue.extend({
  template: '#app',
  mixins: [cartMixin],
  data(){
    return {
      cart: []
    }
  }
})

We call Vue.extend to create a subclass of the Vue constructor.

We can then make a new instance of Store and render that in our app.

Conclusion

To share a method between components in Vue, we can create a module that exports the method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *