vue中如何调取api_如何在Vue.js中构造API调用?

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?

解决方案

I am using axios as HTTP client for making api calls, I have created a gateways folder in my src folder and I have put 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'

}

})

Now in your component, You can have a function which will fetch data from the api like following:

methods: {

getProducts () {

myApi.get('products?id=' + prodId).then(response => this.product = response.data)

}

}

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:

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值