/vuejs-ajax

It is a XHR plugin that works in specific features for Vue.js 2.x and and above versions. Supports file uploading, async & dynamic component plugins, HTML5 pushstate.

Primary LanguageJavaScriptMIT LicenseMIT

vuejs-ajax

Travis Build Version Downloads

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:

Setup

npm install vuejs-ajax --save

You have two ways to setup vuejs-ajax:

CommonJS (Webpack/Browserify)

1 - ES6
import ajax from "vuejs-ajax"
Vue.use(ajax)
2 - ES5
var ajax = require("vuejs-ajax")
Vue.use(ajax)

componentShifter()

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])

Important benefits:

  1. You can organize the async and dynamic components by typing less. Check out the events for listeners.
  2. You can easily prepare common callbacks and listeners for dynamic components.
  3. With the keepAlive option caches the active components. Thus, when inactive components are called, they are loaded quickly without consuming data.
  4. With the library option you can create dynamic options for dynamic component instances (data, props, computed, ..., etc).
  5. And supports Vue.ajax's all features (history, data, title, ..., etc).

Basic Example

this.componentShifter({
    is: {componentHolder: componentName},
    url: url,
}, function() {
    console.log("Component changed!");
});

Options

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)

keepAlive options

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.

Callbacks

Property Required Type Description
success No Function Your custom callback on success. (Second argument)
error No Function Your custom callback on error. (Third argument)
Detailed example

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")
        }
    }
});

Component Shifter Events

componentshiftercomplete

Register a handler to be called when componentShifter() requests complete.

window.addEventListener("vueajaxhistorycomplete", function(e) {
    console.log(e);
});

componentshiftererror

Register a handler to be called when componentShifter() requests complete with an error.

window.addEventListener("componentshiftererror", function(e) {
    console.log(e);
});

componentshifterstart

Register a handler to be called when componentShifter() requests begins.

window.addEventListener("componentshifterstart", function(e) {
    console.log(e);
});

componentshiftersuccess

Attach a function to be executed whenever an componentShifter() request completes successfully.

window.addEventListener("componentshiftersuccess", function(e) {
    console.log(e);
});

Vue.ajax()

Examples

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)
})

Get Method

Vue.ajax.get(string url[, object data] [,object configurations])
    .then(function success[, function error])

Post Method

Vue.ajax.post(string url[, object data] [,object configurations])
    .then(function success[, function error])

Arguments

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.
All ajax request methods and uses are the same:
  • 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)
})

Ajax Configurations

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

Ajax Configuration Examples

Assets

Assets setting is used to push new asset files (CSS or JS) in the document.

Pushing single asset file
Vue.ajax.get([url], [data], {
    assets: "path/css/style.css"
});
Pushing multiple asset files
Vue.ajax.get("http://example.com", {}, {
    assets: ["assets/css/style.css", "assets/js/script.js"]
});

Asynchronous

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
});

Cache

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
});

Complete

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)
    }
});

CSRF

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

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"
    }
});

File Uploading

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>

Hard Reload

Option to hard reloading when page can not be loaded. Default value is false.

Vue.ajax.get("http://example.com", {}, {
    hardReloadOnError: true
});

History

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
});

Adding version for history

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">

HTTP Headers

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, */*"
    }
});

Method

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", {});

Prevent Duplicate Requests

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"
});

Scroll Top

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
});

Timeout

Set a timeout (in milliseconds) for the request. Default value is 60000.

Vue.ajax.get("http://example.com", {}, {
    timeout: 60000
});

Title

Title setting is used to change the document title value.

Vue.ajax.get("http://example.com", {}, {
    title: "New title"
});

URL Data

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

With Credentials

There is a detailed explanation here. Default value is false.

Vue.ajax.get("http://example.com", data, {
    withCredentials: false
});

Response Handling

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

Response Format

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)
    });

Error Handling

There are two ways to use:

1 - In then() method
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"
2 - In catch() method
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"

Event Handlers

Common Events

vueajaxabort

Register a handler to be called when Vue.ajax requests abort.

window.addEventListener("vueajaxabort", function(e) {
    console.log(e);
});

vueajaxcomplete

Register a handler to be called when Vue.ajax requests complete.

window.addEventListener("vueajaxsuccess", function(e) {
    console.log(e);
});

vueajaxerror

Register a handler to be called when Vue.ajax requests complete with an error.

window.addEventListener("vueajaxerror", function(e) {
    console.log(e);
});

vueajaxstart

Register a handler to be called when Vue.ajax requests begins.

window.addEventListener("vueajaxstart", function(e) {
    console.log(e);
});

vueajaxsuccess

Attach a function to be executed whenever an Vue.ajax request completes successfully.

window.addEventListener("vueajaxsuccess", function(e) {
    console.log(e);
});

History Events

vueajaxhistorycomplete

Register a handler to be called when Vue.ajax history requests complete.

window.addEventListener("vueajaxhistorycomplete", function(e) {
    console.log(e);
});

vueajaxhistoryerror

Register a handler to be called when Vue.ajax history requests complete with an error.

window.addEventListener("vueajaxhistoryerror", function(e) {
    console.log(e);
});

vueajaxhistorystart

Register a handler to be called when Vue.ajax history requests begins.

window.addEventListener("vueajaxhistorystart", function(e) {
    console.log(e);
});

vueajaxhistorysuccess

Attach a function to be executed whenever an Vue.ajax history request completes successfully.

window.addEventListener("vueajaxhistorysuccess", function(e) {
    console.log(e);
});

License

MIT

Copyright (c) 2018 Fatih Koca