Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace vue-resource with axios #4

Open
grantcarthew opened this issue Mar 23, 2017 · 0 comments
Open

Replace vue-resource with axios #4

grantcarthew opened this issue Mar 23, 2017 · 0 comments

Comments

@grantcarthew
Copy link
Collaborator

axios is a Promise based HTTP client for the browser and node.js.

To add it to Vue make a plugin.

Here is an example. Create a plugin-http.js file in a plugins directory:

import axios from 'axios'

function interceptResponse (response) {
  // something
}

function interceptRequest (config) {
  // something
}

axios.interceptors.request.use(interceptRequest)
axios.interceptors.response.use(interceptResponse, // catch errors)

const api = {
  install (Vue) {
    Vue.prototype.$api = axios.create({
      baseURL: `/api/`,
      headers: {
        Authorization: 'Bearer {token}'
      }
    })
  }
}

// Automatic installation if Vue has been added to the global scope.
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(api)
}

export default api

An index.js for the plugins directory:

export {default as api} from './plugin-api'
export {default as logging} from './plugin-logging'

In main.js install the plugin with:

import * as plugins from './plugins'
Vue.use(plugins.logging)
Vue.use(plugins.api)

Now you can use the $api property on any Vue or this object:

  mounted () {
    this.signInModal = new Foundation.Reveal($('#signin-modal'))
    this.offCanvas = new Foundation.OffCanvas($('#off-canvas'))
    this.$api.get('/auth/verify')
    .then(function (response) {
      log.info(response)
    })
    .catch(function (error) {
      log.error(error)
    })
    this.signInModal.$element.foundation('open')
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant