vue 最佳实践 api 处理

vue bestpractice api handling

一直在阅读文档并在谷歌上搜索最佳实践来处理 api 较大项目中的调用,但运气不佳(或者至少不是我正在搜索的内容)。

我想为后端创建一个服务/外观,我可以在每个需要它的组件中加载它。例如。

我想在服务中获取天气的历史数据,因此在我需要的每个组件中,我只需加载天气服务并使用 getter 来获取想要的数据。我想以下面的内容结束。但我不想让它工作。所以我想知道,vue.js 中对此的最佳做法是什么?

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

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

ps。使用 vue 2.1.10

这可以通过创建一些外部对象来轻松完成,这些对象将保存这些数据和模块 bundling.What 我通常在我的项目中做的是创建 services 目录并将它们按我想要的顺序分组.

让我们分解一下 - services/WeatherFascade.js(使用 VueResource)

import Vue from 'vue'

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

如果必须传递一些动态数据,比如ID,直接作为参数传递

import Vue from 'vue'

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

然后在您的组件中您可以导入此服务,传递参数(如果有)并取回数据。

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))
    }
  }
}

您可以使用任何您喜欢的库,例如 axios 很酷。