Skip to main content
Category:

Installation

You can install it via yarn or NPM.

$ yarn add vue-resource
$ npm install vue-resource

 

Import in our application

Next, open file main.js and insert the following import statement:

import VueResource from 'vue-resource'

In addition add the following line of code right under the import statements:

Vue.use(VueResource);

Now we're ready to use vue-resource within our components.

 

How to use this library:

The http service can be used globally Vue.http or in a Vue instance this.$http.

A Vue instance provides the this.$http service which can send HTTP requests. A request method call returns a Promise that resolves to the response. Also the Vue instance will be automatically bound to this in all function callbacks.

{
  // GET /someUrl
  this.$http.get('/someUrl').then(response => {
    // success callback
  }, response => {
    // error callback
  });
}

Methods:

Shortcut methods are available for all request types. These methods work globally or in a Vue instance.

// global Vue object
Vue.http.get('/someUrl', [config]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);

// in a Vue instance
this.$http.get('/someUrl', [config]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);

List of shortcut methods:

  • get(url, [config])
  • head(url, [config])
  • delete(url, [config])
  • jsonp(url, [config])
  • post(url, [body], [config])
  • put(url, [body], [config])
  • patch(url, [body], [config])

 

Example how to use in a component:

Example get call:

<template>
  <div class="sourceselection">
    <div>
      <div class="jumbotron">
        <h2><span class="glyphicon glyphicon-list-alt"></span>&nbsp;News List</h2>
        <h4>Select News Source</h4>
        <select class="form-control" v-on:change="sourceChanged">
          <option value="">Please select news source ...</option>
          <option v-for="source in sources" v-bind:value="source.id">{{source.name}}</option>
        </select>
        <div v-if="source">
          <h6>{{source.description}}</h6>
          <a v-bind:href="source.url" class="btn btn-primary" target="_blank">Go To {{source.name}} Website</a>
        </div>
      </div>
    </div>
  </div>
</template><script>
export default {
  name: 'sourceselection',
  data () {
    return {
      sources: [],
      source: ''
    }
  },
  methods: {
    sourceChanged: function(e) {
     for (var i=0; i<this.sources.length; i++) {
       if (this.sources[i].id == e.target.value) {
         this.source = this.sources[i];
       }
     }
     this.$emit('sourceChanged', e.target.value);
    }
  },
  created: function () {
    this.$http.get('https://newsapi.org/v1/sources?language=en')
      .then(response => {
        this.sources = response.data.sources;
      });
  }
}
</script>

 

Example post call:

{
  // POST /someUrl
  this.$http.post('/someUrl', {foo: 'bar'}).then(response => {

    // get status
    response.status;

    // get status text
    response.statusText;

    // get 'Expires' header
    response.headers.get('Expires');

    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });
}

 

Building Flexible API Client

I you prefer to build specific API JS modules that you can import into any components and Vuex modules. Building API resource modules allows you to abstract working with HTTP resources, and provide convenience methods for common patterns. here is an example how to create API Client:

 

Example:

import Vue from "vue";
import VueResource from 'vue-resource'

Vue.use(VueResource);

Vue.http.interceptors.push(function (request) {

  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  const baseUrl = 'http://dev.apilaravel.com/api/';

  request.headers.set('Accept', 'application/json');
  request.url = baseUrl + request.url;
  if (currentUser) {
    request.headers.set('Authorization', 'Bearer ' + currentUser.token);
    request.headers.set('role', '' + currentUser.role === '0' ? 'admin' : 'editor');
  }

});

export class ApiClient {

  get(url) {
    return Vue.http.get(url)
      .then(response => Promise.resolve(response.data))
      .catch(error => Promise.reject(error));
  }

  post(url, data) {
    return Vue.http.post(url, data)
      .then(response => Promise.resolve(response.data))
      .catch(error => Promise.reject(error));
  }

  update(url, data) {
    return Vue.http.put(url, data)
      .then(response => Promise.resolve(response.data))
      .catch(error => Promise.reject(error));
  }

  delete(url) {
    return Vue.http.delete(url)
      .then(response => Promise.resolve(response.data))
      .catch(error => Promise.reject(error));
  }

}


 

Using client.js to Make API Clients

Using the above client, you can now build your own specific  services for managing articles for example.

Example ArticlesService.js :


import {ApiClient} from '../services/client';

let apiClient = new ApiClient();

export default {

  post(article) {
    return apiClient.post('articles/add', article);
  },
  update(id, article) {
    return apiClient.update('articles/' + id + '/update', article);
  },
  getByID(id) {
    return apiClient.get('articles/' + id);
  },
  get(nbrePage){
    return apiClient.get('articles' + '?page=' + nbrePage);
  },
  delete(id){
    return apiClient.delete('articles/' + id);
  },
  recherche(article){
    return apiClient.post('articles', article);
  },
  export(article){
    return apiClient.post('articles', article);
  }

}

 

Example how to use our service in component :

    methods: {
    
      createArticle() {
        let article = new FormData();
        article.append('title', this.article.title);
        article.append('author', this.article.author);
        article.append('published_at', this.article.published_at);
        article.append('image', this.article.image);
        article.append('body', this.article.body);
        ArticleService.post(article).then(response => {
          if (response.status == 201) {
            this.$router.push('/articles');
          } else {
            this.showAlert = true;
            this.colorAlert = 'danger';
            this.messageAlert = "failed operation";
          }
        }, error => {
          this.showAlert = true;
          this.colorAlert = 'danger';
          this.messageAlert = 'failed operation' + error.toString();
        });
      }
    },

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook