Sometimes, we want to share a method between components in Vue.js.
In this article, we’ll look at how to share a method between components in Vue.js.
How to share a method between components in Vue.js?
To share a method between components in Vue.js, we can use mixins.
For instance, we write
mixins/cartMixin.js
export default {
methods: {
addToCart() {
//...
},
},
};
to create the cartMixin.js
module that exports an object with the addToCart
method inside.
Then we use the mixin in our component by writing
<script>
import cartMixin from "./mixins/cartMixin.js";
//...
export default {
//...
mixins: [cartMixin],
//...
};
</script>
We set mixins
to an array with the cartMixin
inside to incorporate the addToCart
method from the mixin into our component.
Conclusion
To share a method between components in Vue.js, we can use mixins.