Jedi Schmedi
Jedi Schmedi

Reputation: 818

vue bestpractice api handling

Been reading the docs and googling around for best practice to handle api calls in bigger projects without luck (or ateast not what Im searching for).

I want to create a service / facade for the backend that I can load in every component that needs it. For exampel.

I want to fetch historical data for weather in a service so in every component I need this I can just load the weather-serivce and use a getter to fetch the wanted data. I would like to end up with something like below. But I dosent get it to work. So I wonder, what is best practice for this in vue.js?

import WeatherFacade from './data/WeatherFacade.vue'

export default {
  name: 'Chart',
  created () {
    console.log(WeatherFacade.getWeather())
  },
  components: {
    WeatherFacade 
  }
}

ps. using vue 2.1.10

Upvotes: 2

Views: 912

Answers (1)

Belmin Bedak
Belmin Bedak

Reputation: 9201

It could be easily done by creating some external object that will hold those data and module bundling.What I usually do in my projects is that I create services directory and group them in order I want.

Let's break it down - services/WeatherFascade.js (using VueResource)

import Vue from 'vue'

export default {
  getWeather() {
    return Vue.http.get('api/weather')
  }
}

If you have to pass some dynamic data such as ID, pass it as just parameter

import Vue from 'vue'

export default {
  getWeather(id) {
    return Vue.http.get(`api/weather/${id}`)
  }
}

Then in your component you can import this service, pass parameters (if you have them) and got data back.

import WeatherFascade from '../services/WeatherFascade'

export default {
  data() {
    return {
      weatherItems: []
    }
  },
  created() {
    this.getWeatherData()
  },
  methods: {
    getWeatherData() {
      WeatherFascade.getWather(// you can pass params here)
       .then(response => this.weatherItems = response.data)
       .catch(error => console.log(error))
    }
  }
}

You can use any library for that you like, for instance axios is cool.

Upvotes: 1

Related Questions