Search code examples
javascriptvue.jsvuejs2vue-componentvuex

Vuejs - Get different date in the same component


I have created several components (tables, selects, etc) and all use the same methods to get API information.

The purpose is to use these components on different pages of the application and as such, so that one can use the same component (eg table) regardless of the information it receives, I have created a number of methods to allow this.

However, to apply these methods to all components requesting the API, you would have to repeat a lot of code, and as such the goal is to create these methods globally.

After a search I found three ways to do it, with Plugins, Mixins and Vuex. However I do not know what is the most ideal way to do this.

Any suggestion?


Solution

  • Go with Vuex.

    Create a centralized store where your components interact with its data using getters, actions and mutations, and the store knows how to interact with the API.

    For example, your table component can be dumb, and just expect a :data=someData that the component that initializes the table passes to it, then it just renders whatever was passed. This someData can be mapped to a Vuex getter (or directly to an item in the store state) in the parent component.

    When your component needs to have something submitted to the API, it can trigger an event the parent will pick up and call the appropriate action or mutation on the store, the store will know what to call in the API to do this action. So, even your parent isn't completely aware on how the API works, just your abstraction of if, represented by your Vuex store.

    I have created a very simple todos application last week for another question here, feel free to have a look, uses Vue, Vuex and saves the data to Firebase. It also doesn't implement REST as it could, but it isn't too hard to change the store to use the proper REST methods get, post, put, delete etc.

    All the relevant code of this application in in App.vue and store.js, with one line in main.js just to add the store to the Vue instance.