martinho
martinho

Reputation: 1016

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?

Upvotes: 1

Views: 405

Answers (2)

a--m
a--m

Reputation: 4782

Vuex will help with shared/own components state. If your problem is how to manage shared API call Vuex persi won't tackle that problem directly. It will help you once you get that data accessible to your components.

That said, you can create a module to do the API call and retrieve data, say:

http.js

export const getUser = async id => {      
  const response = await fetch(`/user/${id}`)
  return await response.json()
}

export const getContent = async id => {      
  const response = await fetch(`/content/${id}`)
  return await response.json()
}

This is a solution that will help you both with or without Vuex, now you can call those methods from anywhere.

Upvotes: 1

Leite
Leite

Reputation: 994

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.

Upvotes: 1

Related Questions