It is a XHR plugin that works in specific features for Vue.js 2.x and and above versions. It has many similar features with jQuery
's ajax()
and Angular
's $http()
. In addition to these, it also has its own important features:
Assets
Component shifter
Event handlers
File uploading
History
Title
Serialized query string
Prevent duplicate requests
npm install vuejs-ajax --save
You have two ways to setup vuejs-ajax
:
import ajax from "vuejs-ajax"
Vue.use(ajax)
var ajax = require("vuejs-ajax")
Vue.use(ajax)
With componentShifter() you can load (with Vue.ajax
) and render your Vue template
(html) in your application by dynamic & async Vue.component()
. You can also add components and run them nested.
this.componentShifter(object configurations[, function success] [,function error])
- You can organize the
async and dynamic components
by typing less. Check out the events for listeners. - You can easily prepare common
callbacks
andlisteners
for dynamic components. - With the
keepAlive
option caches the active components. Thus, when inactive components are called, they are loaded quickly without consuming data. - With the
library
option you can create dynamic options for dynamic component instances (data
,props
,computed
, ..., etc). - And supports
Vue.ajax
's all features (history
,data
,title
, ..., etc).
this.componentShifter({
is: {componentHolder: componentName},
url: url,
}, function() {
console.log("Component changed!");
});
Property | Required | Type | Description |
---|---|---|---|
is |
Yes | Object | Component holder (key) and unique component name (value). |
url |
Yes | String | Component resources url. |
keepAlive |
No | Boolean or object | Caches the inactive components. Default: false |
library |
No | Object | Options of the new component instance (data , props , ..., etc) |
Property | Required | Type | Description |
---|---|---|---|
include |
No | Array, string (comma-delimited), regex | Only components with matching names will be cached. |
exclude |
No | Array, string (comma-delimited), regex | Any component with a matching name will not be cached. |
max |
No | Number | The maximum number of component instances to cache. |
Property | Required | Type | Description |
---|---|---|---|
success |
No | Function | Your custom callback on success. (Second argument) |
error |
No | Function | Your custom callback on error. (Third argument) |
HTML
<div id="app">
<a href="/page-1" @click.prevent="openPage('page1', '/page-1', 'Page 1')">Page 1</a>
<a href="/page-2" @click.prevent="openPage('page2', '/page-2', 'Page 2')">Page 2</a>
<a href="/page-3" @click.prevent="openPage('page3', '/page-3', 'Page 3')">Page 3</a>
<!-- Your container component -->
<component :is="pageComponent"></component>
</div>
Vue.js
new Vue({
el: "#app",
data() {
return {
pageComponent: null, // Component holder
pageLoaded: false
}
},
methods: {
openPage(componentName, url, title) {
// Calling componentShifter
this.componentShifter({
is: {pageComponent: componentName},
url: url,
keepAlive: {
max: 10,
// Another usages: "page1,page2" and /page1|page2/
include: ["page1", "page2"],
// Another usages: "page3,page4" and /page3|page4/
exclude: ["page3", "page4"]
},
library: {
data() {
return {
hasFooter: true
}
},
props: ["custom"]
}
}, function() {
console.log("Component changed!");
this.pageLoaded = true;
}, function(response) {
console.log("Component could not be changed!", response);
this.pageLoaded = false;
});
}
},
mounted() {
if(!pageLoaded) {
this.openPage("page1", "/page-1", "Page 1")
}
}
});
Register a handler to be called when componentShifter()
requests complete.
window.addEventListener("vueajaxhistorycomplete", function(e) {
console.log(e);
});
Register a handler to be called when componentShifter()
requests complete with an error.
window.addEventListener("componentshiftererror", function(e) {
console.log(e);
});
Register a handler to be called when componentShifter()
requests begins.
window.addEventListener("componentshifterstart", function(e) {
console.log(e);
});
Attach a function to be executed whenever an componentShifter()
request completes successfully.
window.addEventListener("componentshiftersuccess", function(e) {
console.log(e);
});
Vue.ajax.get("http://example.com").then(function(response) {
console.log("Success", response.data)
}, function(response) {
console.log("Error", response.statusText)
});
If you want to send data to the backend:
Vue.ajax.get("http://example.com", {
param1: "First parameter",
param2: "Second parameter"
}).then(function(response) {
console.log("Success", response.data)
}, function(response) {
console.log("Error", response.statusText)
})
Or if you want to make some configurations:
Vue.ajax.get("http://example.com", {
param: "Send parameter"
}, {
history: true,
scrollTop: true,
}).then(function(response) {
console.log("Success", response.data)
}, function(response) {
console.log("Error", response.statusText)
})
Vue.ajax.get(string url[, object data] [,object configurations])
.then(function success[, function error])
Vue.ajax.post(string url[, object data] [,object configurations])
.then(function success[, function error])
Property | Required | Type | Description |
---|---|---|---|
url | Yes | String | A string containing the URL to which the request is sent. |
data | No | Object | A plain object that is sent to the server with the request. |
configurations | No | Object | A set of key/value pairs that configure the Vue.ajax request. |
- Delete method:
Vue.ajax.delete(...)
- Get method:
Vue.ajax.get(...)
- Head method:
Vue.ajax.head(...)
- Jsonp method:
Vue.ajax.jsonp(...)
- Patch method:
Vue.ajax.patch(...)
- Post method:
Vue.ajax.post(...)
- Put method:
Vue.ajax.put(...)
All of the above methods are a shorthand method of the Vue.ajax()
:
Vue.ajax({
url: "http://example.com",
method: "get" // post, put, patch, delete, head, jsonp
}).then(function(response) {
console.log("Success", response.data)
}, function(response) {
console.log("Error", response.statusText)
})
Configuration | Type | Default | Available |
---|---|---|---|
assets |
String Or Object | - | - |
async |
Boolean | true | true, false |
cache |
Boolean | false | true, false |
complete |
Function | - | - |
csrf |
Boolean | true | true, false |
data |
Object | - | - |
fileInputs |
Element Object | - | Input file upload objects |
hardReloadOnError |
Boolean | false | true, false |
history |
Boolean | false | true, false |
headers |
Object | - | - |
method |
String | get | delete, get, head, jsonp, patch, post, put |
preventDuplicate |
Boolean | true | true, false |
scrollTop |
Boolean | false | true, false |
timeout |
Integer | 60000 | Time in milliseconds |
title |
String | - | - |
url |
String | - | - |
urlData |
Object | - | - |
withCredentials |
Boolean | false | true, false |
Assets setting is used to push new asset files (CSS or JS) in the document.
Vue.ajax.get([url], [data], {
assets: "path/css/style.css"
});
Vue.ajax.get("http://example.com", {}, {
assets: ["assets/css/style.css", "assets/js/script.js"]
});
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false
. Default value is true
.
Vue.ajax.get("http://example.com", {}, {
async: true
});
If set to false, it will force requested pages not to be cached by the browser. Default value is false
.
Vue.ajax.get("http://example.com", {}, {
cache: false
});
A function to be called when the request finishes (Success
or error
callbacks are executed).
Vue.ajax.get("http://example.com", {}, {
complete: function(response) {
console.log(response.status)
}
});
This setting provides protection against CSRF attacks. There is a detailed explanation here
. Default value is true
.
Vue.ajax.get("http://example.com", {}, {
csrf: true
});
In the html head tag it must be csrf-token
meta
. Like this:
<meta name="csrf-token" content="[TOKEN]">
Data to be sent to the server.
Vue.ajax("http://example.com", {
url: "http://example.com",
method: "get",
data: {
param1: "First parameter",
param2: "Second parameter"
}
});
fileInputs
setting should be DOM object
<input type="file">
. We recommend using the post
method when uploading files.
The important thing here is that you should not forget the name
attribute.
HTML:
<input type="file" name="my-input" id="my-input">
Vue.js:
Vue.ajax.post("http://example.com", {}, {
fileInputs: [
document.getElementById("my-input")
]
});
You can only add the accept
attribute to send images.
<input type="file" name="my-input-2" id="my-input-2" accept="image/*">
You can add the multiple
attribute to send multiple files with an input element:
<input type="file" name="my-input-3" id="my-input-3" multiple>
Option to hard reloading when page can not be loaded. Default value is false
.
Vue.ajax.get("http://example.com", {}, {
hardReloadOnError: true
});
History setting is usage of PushState (HTML history API). Default value is false
.
PushState (changing the URL of the page without refreshing the page) to create a faster browsing experience. This means less elements to load and therefore faster browsing.
Vue.ajax.get("http://example.com", {}, {
history: true
});
Layouts can be forced to do a hard reload when assets or html changes. First set the initial layout version in your header with a custom meta
tag.
HTML:
<meta http-equiv="x-history-version" content="ABCDEFGH">
An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport.
Vue.ajax.get("http://example.com", {}, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*"
}
});
The HTTP method to use for the request (e.g. "get", "post", "put"). Default value is get
.
Vue.ajax({
url: "http://example.com",
method: "post"
});
Instead, you might prefer to use the following shorthand:
Vue.ajax.post("http://example.com", {});
This setting prevents sending duplicate requests to the same address or given key data. Default value is true
.
The following example prevents sending requests over the same URL:
Vue.ajax.get("http://example.com", {}, {
preventDuplicate: true
});
The following example prevents sending requests over the same given key data:
Vue.ajax.get("http://example.com", {}, {
preventDuplicate: true,
key: "ABCDEFGH"
});
This setting is used to scroll to top of the document when after loading the request. Default value is true
.
Vue.ajax.get("http://example.com", {}, {
scrollTop: true
});
Set a timeout (in milliseconds) for the request. Default value is 60000
.
Vue.ajax.get("http://example.com", {}, {
timeout: 60000
});
Title setting is used to change the document title value.
Vue.ajax.get("http://example.com", {}, {
title: "New title"
});
With this setting, you can add serialized query string to the URL you are sending.
Vue.ajax.get("http://example.com", {}, {
urlData: [
{category: "Accessories"},
{page: 15}
]
});
The URL will be like this when sending the request:
http://example.com?category=Accessories&page=15
There is a detailed explanation
here.
Default value is false
.
Vue.ajax.get("http://example.com", data, {
withCredentials: false
});
The response returns the Object on the frontend.
Success and error together in then()
method:
Vue.ajax({url: "http://example.com"})
.then(function(response) {
console.log(response.data);
}, function(response) {
console.log(response);
})
Success and error together in in separate methods:
Vue.ajax({url: "http://example.com"})
.then(function(response) {
console.log(response.data);
})
.catch(function(response) {
console.log(response);
})
The object in general is the following structure:
Vue.ajax.post("http://example.com", {pageNumber: 5})
.then(function(response) {
console.log(response.data)
});
Response Property | Type |
---|---|
data | Object Or String |
status | String |
statusText | String |
headers | String |
config | Object |
xhrStatus | String |
request | Object |
If the content type on the server is "application/json
", the response.data
is automatically converted to a JSON object
. If the content type is anything else, the result is returned as plain text
.
PHP:
header("Content-type: application/json; charset=utf-8");
echo json_encode($array);
PHP (Laravel):
Route::get("http://example.com", function () {
return json_encode($array);
});
Vue.js
Vue.ajax.get("http://example.com", {})
.then(function(response) {
console.log(response.data)
});
There are two ways to use:
Vue.ajax.get("http://example.com/not-existing-path", [data])
.then(function(response) {
console.log(response.data)
}, function(response) {
console.log("Error: ", response.statusText);
}); // "Error: Not Found"
Vue.ajax.get("http://example.com/not-existing-path", [data])
.then(function(response) {
console.log(response.data)
}).catch(function(response) {
console.log("Error: ", response.statusText);
}); // "Error: Not Found"
Register a handler to be called when Vue.ajax
requests abort.
window.addEventListener("vueajaxabort", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax
requests complete.
window.addEventListener("vueajaxsuccess", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax
requests complete with an error.
window.addEventListener("vueajaxerror", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax
requests begins.
window.addEventListener("vueajaxstart", function(e) {
console.log(e);
});
Attach a function to be executed whenever an Vue.ajax
request completes successfully.
window.addEventListener("vueajaxsuccess", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax history
requests complete.
window.addEventListener("vueajaxhistorycomplete", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax history
requests complete with an error.
window.addEventListener("vueajaxhistoryerror", function(e) {
console.log(e);
});
Register a handler to be called when Vue.ajax history
requests begins.
window.addEventListener("vueajaxhistorystart", function(e) {
console.log(e);
});
Attach a function to be executed whenever an Vue.ajax history
request completes successfully.
window.addEventListener("vueajaxhistorysuccess", function(e) {
console.log(e);
});
Copyright (c) 2018 Fatih Koca