I use axios as an HTTP client to make API calls, I created a gateways folder in my src folder and I have files for each backend, creating axios instances , like the following
myApi.js
import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:3000/api/v1', timeout: 5000, headers: { 'X-Auth-Token': 'f2b6637ddf355a476918940289c0be016a4fe99e3b69c83d', 'Content-Type': 'application/json' } })
The same instances are used both for component actions and for vuex to receive data, the following details of both methods.
Component data
If the data is used only in the component, for example, in your case Messages.vue , you can get a method that will extract data from the api as follows:
export default { name: 'myComponent', data: () => ({ contents: '', product: [] }), props: ['abc'], methods: { getProducts (prodId) { myApi.get('products?id=' + prodId).then(response => this.product = response.data) }, error => { console.log('Inside error, fetching products failed')
Filling Vuex Data
If you support product-related data in a dedicated vuex module , you can send an action from a method in the component that will call the backend API internally and populate the data in the repository, the code will look something like this:
Code in component:
methods: { getProducts (prodId) { this.$store.dispatch('FETCH_PRODUCTS', prodId) } }
Code in vuex repository:
import myApi from '../../gateways/my-api' const state = { products: [] } const actions = { FETCH_PRODUCTS: (state, prodId) => { myApi.get('products?id=' + prodId).then(response => state.commit('SET_PRODUCTS', response)) } } // mutations const mutations = { SET_PRODUCTS: (state, data) => { state.products = Object.assign({}, response.data) } } const getters = { } export default { state, mutations, actions, getters }