I want to put all my functions that talk to the server and fetch data into a single reusable file in VueJS.
Plugins don't seem to be the best alternative. Template less components..?
I want to put all my functions that talk to the server and fetch data into a single reusable file in VueJS.
Plugins don't seem to be the best alternative. Template less components..?
There are 4 ways:
I suggest creating an API Provider that you can access from anywhere in your app.
Simply create a
src/utils
folder and inside of it a file calledapi.js
.In it, export your wrapper that knows how to communicate with your API as an object or a ES6 static class (I prefer how the latter looks and works if you're not afraid of classes). This provider can use any HTTP request library that you like and you can easily swap it later by changing a single file (this one) instead of hunting down the whole codebase. Here's an example of using axios, assuming we have a REST API available at
api.example.com/v1
that uses SSL:Next, in your
main.js
file or wherever else you bootstrap the Vue app, do the following:Now you can access it anywhere in your Vue app as well as anywhere you import Vue itself:
or:
Hope this helps.
I'm using Vue Resource mostly.
1.I create new file where I do connection to API endpoint using
Vue.http.xxx
.So let's say we have endpoint that output the posts.Create new directory in your project, I call itservices
, and then create file calledPostsService.js
- content looks like this:Then I go to component where I want use this service, and import it
For more info about this approach, feel free to check my repo on GitHub https://github.com/bedakb/vuewp/tree/master/public/app/themes/vuewp/app
I am using axios as HTTP client for making api calls, I have created a
gateways
folder in mysrc
folder and I have put files for each backend, creating axios instances, like followingmyApi.js
Now in your component, You can have a function which will fetch data from the api like following:
As I assume you want to re-use this method in multiple components, you can use mixins of vue.js:
So you can add a method in mixin and it will be available in all the components, where mixin will be mixed. See following example:
I think for your simple question the answer could be any ES6 module containing functions (equivalent to methods in class in ANgular) and directly importing them in components using ES6 imports and exports. There are no such services that could be injected in components.