How do I place the Vue-resource in an external file for better separation of concerns?
and how do I call it from a component?
Currently I do this:
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.http.options.root = '/api/public/v1.0'
Vue.http.headers.common['Access-Control-Allow-Origin'] = 'http://api.movies.com/'
export default class Resource {
getMovies (url, currentPage, query) {
let params = {
params: {
'page_limit': 10,
'page': currentPage,
'country': 'us',
'apikey': 'qwertyuio',
'q': query
}
}
return Vue.http.get(url, params).then((response) => {
return response.json()
}).catch(function (e) {
console.log(e)
return false
})
}
}
and in my component:
import Resource from '../../services/resource'
const resourceService = new Resource()
...
methods: {
getMovies: function (url, page, query) {
console.log(query)
this.loading = true
resourceService.getMovies(url, page, query).then((result) => {
this.items = result.movies
this.totalMovies = result.total
this.loading = false
})
},
Typically i create an API directory structured like this...
api/
index.js
user.js
...
The index simply imports each module so everything can be accessed as one module...
import './users';
And each module contains the calls for a specific part of the API...
import Vue from 'vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);
/**
* Get all users.
*
* @param {integer} id
*
* @return {Promise}
*/
export const getAllUsers = () => {
return Vue.http.get('https://example.com/api/v1/users');
};
All that is left to do is import the module in your component or state (_depending on how you want to tackle it_) and you are good to go.
import {getAllUsers} from './api/users';
getAllUsers().then(users => {
// handle the users.
}).catch(error => {
// handle the errors.
});
Most helpful comment
Typically i create an API directory structured like this...
The index simply imports each module so everything can be accessed as one module...
And each module contains the calls for a specific part of the API...
All that is left to do is import the module in your component or state (_depending on how you want to tackle it_) and you are good to go.