How to structure api calls in Vue.js?

前端 未结 3 1766
长情又很酷
长情又很酷 2021-01-30 06:38

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 sha

相关标签:
3条回答
  • 2021-01-30 07:19

    Note: vue-resource is retired ! Use something else, such as Axios.

    I'm using mostly Vue Resource.I create services directory, and there put all connections to endpoints, for e.g PostService.js

    import Vue from 'vue'
    
    export default {
      get(id) {
        return Vue.http.get(`/api/post/${id}`)
      },
      create() {
        return Vue.http.post('/api/posts') 
      }
      // etc
    }
    

    Then in my file I'm importing that service and create method that would call method from service file

    SomeView.vue

    import PostService from '../services/PostService'
    
    export default {
      data() {
        item: []
      },
      created() {
        this.fetchItem()
      },
      methods: {
        fetchItem() {
          return PostService.get(to.params.id)
            .then(result => {
              this.item = result.json()
            })
        }  
      }
    }
    
    0 讨论(0)
  • 2021-01-30 07:20

    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

    // GET /posts?filter[status]=ACTIVE
    
    let post = await Post
      .where('status', 'ACTIVE')
      .get()
    

    Specific result

    // GET /posts/1
    
    let post = await Post.find(1)
    

    Editing

    // PUT /posts/1 
    
    post.title = 'Awsome!'
    post.save()
    

    Relationships

    // GET /users/1
    let user = await User.find(1)
    
    // GET users/1/posts
    let posts = await user
      .posts()
      .get()
    
    0 讨论(0)
  • 2021-01-30 07:25

    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)
提交回复
热议问题