I'm currently working on a new Vue.js application. It depends heavily on api calls to my backend database.
For a lot of things I use Vuex stores because it manages shared data between my components. When looking at other Vue projects on github I see a special vuex directory with files that handles all the actions, states and so on. So when a component has to call the API, it includes the actions file from the vuex directory.
But, for messages for example, I don't want to use Vuex because those data is only important for one specific view. I want to use the component specific data here. But here is my problem: I still need to query my api. But I shouldn't include the Vuex actions file. So in that way I should create a new actions file. This way I have a specific file with api actions for vuex and for single components.
How should I structure this? Creating a new directory 'api' that handles actions for both vuex data and component-specific data? Or separate it?
Based on concept of Belmin Bedak`s answer, i have wrapped it all into a simple library:
https://github.com/robsontenorio/vue-api-query
You can request your API like this:
All results
Specific result
Editing
Relationships
I am using axios as HTTP client for making api calls, I have created a
gateways
folder in mysrc
folder and I have put files for each backend, creating axios instances, like followingmyApi.js
Now in your component, You can have a function which will fetch data from the api like following:
Similarly you can use this to get data for your vuex store as well.
Edited
If you are maintaining product related data in a dedicate vuex module, you can dispatch an action from the method in component, which will internally call the backend API and populate data in the store, code will look something like following:
Code in component:
Code in vuex store:
I'm using mostly Vue Resource.I create
services
directory, and there put all connections to endpoints, for e.g PostService.jsThen in my file I'm importing that service and create method that would call method from service file
SomeView.vue