How to structure api calls in Vue.js?

前端 未结 3 1805
长情又很酷
长情又很酷 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()
            })
        }  
      }
    }
    

提交回复
热议问题