I am using axios as HTTP client for making API calls, I have created a gateways
folder in my src
folder and I have files for each backend, creating axios instances, like 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'
}
})
These same instances are used in both component and vuex actions to get the data, following are details of both ways.
Populating component data
If the data is being used only in the component, like your case of Messages.vue
, you can have a method which will fetch data from the api like following:
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')
//set error variable here
})
}
.....
Populating Vuex data
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:
methods: {
getProducts (prodId) {
this.$store.dispatch('FETCH_PRODUCTS', prodId)
}
}
Code in vuex store:
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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…