A Vue plugin that setups the vue-resource module and exposes some http utilities methods.
- Import the plugin and register it:
import httpPlugin from "@/../ditto/http";
Vue.use(httpPlugin);
- Use the exposed methods as you wish (the methods are available at
Vue.$http
(orthis.$http
if you have access to a component scope)):
Vue.$http
.get("test")
.then(response => console.log(response))
.catch(error => console.error(error));
Available plugin options:
Option | Description | Default |
---|---|---|
httpRoot | the base url of all the http requests, (see the docs for more information) | / |
addTrailingSlashInterceptor | whether to add an interceptor that adds a trailing slash / to all http request urls, should be used only until the django/vue router bug is resolved @simone |
false |
Vue.use(httpPlugin, {
httpRoot: "/api",
addTrailingSlashInterceptor: true
});
Extensions consists in custom plugins that you want to install after http plugin setup ends. The plugin extensions can access to the http plugin functionalities and can have their options object.
import customPlugin from "...";
const customPluginOptions = {...};
Vue.use(httpPlugin, {
extensions: [
{
plugin: customPlugin,
options: customPluginOptions
}
]
});
The plugin exposes the following methods, available at Vue.$http
(or this.$http
if you have access to a component scope):
addHeader(key, value)
adds a new (key, value) pair to the http headers of all the http requestssetRoot(url)
updates the base url of all the http requests (see options)getUrl(endpoint, params, useRandomString = true)
given an object of params returns the string composed adding to the endpoint string the required request parameters; when useRandomString is true, a random parameter is added to the resulting string (the random parameter is used to prevent request result caching in IE); example:getUrl("test", {a: 1, b: 2})
=>test?a=1&b=2&r=asdfasd
All these methods return a Promise:
get(endpoint, params)
computes the request url using the getUrl function and resolves the promise when the http get request receives a response, returning that response as a json objectpatch(endpoint, params, data)
computes the request url using the getUrl function and resolves the promise when the http patch request receives a response; data is the body of the http requestpost(endpoint, params, data)
computes the request url using the getUrl function and resolves the promise when the http post request receives a response; data is the body of the http requestremove(endpoint, params)
computes the request url using the getUrl function and resolves the promise when the http delete request receives a response
See the http examples code for more information.