Solution to remove and simplify axios in components vue

Overview

Vue fast axios

Solution to remove and simplify axios in components vue

Dependencies:

  • Only Vue.js 2.x

Before install

Before installing, you must install and configure some packages to make use of the plugin.

First, install the babel-polyfill package to allow use async and await keywords:

npm install babel-polyfill --save

To allow, edit the webpack.config.js, replacing the line:

entry: './src/main.js',

To:

entry: ['babel-polyfill', './src/main.js'],

If your want use arrow function in your services, please install transform-class-properties plugin:

npm install babel-plugin-transform-class-properties --save-dev

In your .babelrc file, register this plugin:

{
  ...
  "plugins": [
    "transform-class-properties"
  ]
}

Installation

To install this plugin run:

npm install vue-fast-axios --save

and then, register he in Vue application, in main.js file:

import VueFastAxios from 'vue-fast-axios'
Vue.use(VueFastAxios)

Creating services

An service is compound with follow definitions:

  • base:function | string : return root url for your API

  • headers:function | object : return object with headers for api, use style of axios

  • routes:function | object : return object with routes for api, each route has properties 'methods' and 'path'

  • methods:function | object : return object with alias for async request to route, each method has properties 'method' and 'route'

  • defaultVMessage:function | string : return default message of error to validations

  • validation:function | object : return object with properties to validate, each property has properties 'validator' and 'message'

    See an example:

'use strict'

// Export service skeleton class
export default class PeoplesService {
    // define base url to requests
    base = () => 'https://xxx.firebaseio.com/'

    headers = () => ({
        'Content-Type': 'application/json' // but vue-fast-axios use application/json as default header
    })

    // define routes
    routes = () => ({
        root: { // route name
            methods: 'get,post', // methods accepted in route
            path: 'peoples.json' // path to route, url is: base + prepend + path + append
        },
        peoples: { // route name
            methods: 'put,delete' // methods accepted in route
            // default path route is route name (peoples)
        }
    })

    // methods to call in service instance
    methods = () => ({
        list: { // method name
            method: 'get', // method to htpp request
            route: 'root' // route to call with method
        },
        create: {
            method: 'post',
            route: 'root'
        }
    })

    defaultVMessage = () => 'Error to handle peoples'

    // validations
    validation = () => ({
        name: { // property to validate
            validator: (value) => value.length > 2, // validation
            message: 'Name is invalid' // message to error case
        },
        // simple validator, the error message is 'Error to handle peoples'
        key: (value) => key > 0
    })
}

Using services

In your vue componentes, use method $serviceFactory to create an service with skeleton created before:

<template>
  ...
</template>

<script>
import PeoplesService from './services/PeoplesService' // your service

export default {
  name: 'app',
  data: () => ({
    service: null, // store my service handler
    ...
  }),
  // create my service with PeoplesService rules and pass this to call handle methods
  mounted() {
    this.service = this.$serviceFactory(new PeoplesService, this)
  },
  ...
  }
}
</script>

Now you have an service object, you can run call and execute methods, they has an simple difference:

  • execute(routeName, parameters = {}) | bool : use this to simples and manual requests. To use, you must have the methods serviceSuccess and serviceError, they as called when promise is resolved and receive an object with error or response.
  • call(methodName, parameters = {}) | object: use this for async/await requests. Is an way for execute request and capture response in one line! Erros as exceptions are throwed in console.

To use this methods, your component must have validationError method, they is called when an validation has failed, and receive an message as parameter.

See an metaphorical example:

<template>
  <div id="app">
    <button @click="createPeople">Create people</button>

    <button @click="updatePeople">Update pople</button>

    <ul>
      <li v-for="(people, key) in peoples" :key="key">
        <button @click="deletePeople(key)">Delete</button>
        {{ people.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import PeoplesService from './services/PeoplesService'

export default {
  name: 'app',
  data: () => ({
    service: null, // store my service handler
    peoples: [], // list of peoples
    newPeople: 'Leonardo', // store name from new people
    peopleToUpdate: {key: 1, name: 'New Leonardo'} // people to update
  }),
  // create my service with PeoplesService rules and pass this to call handle methods
  mounted() {
    this.service = this.$serviceFactory(new PeoplesService, this)
    this.load()
  },
  methods: {
    // call list method from PeopleService, with route root and method get
    async load() {
      this.peoples = await this.service.call('list')
    },

    // call create method from PeopleService, with route root and method post, pass object to register
    // this object is validate with 'name' rule from PeopleService
    async createPeople() {
      await this.service.call('create', { name: this.newPeople })
      this.load()
    },

    // append key.json to url, and set delete method. Execute this settings in peoples route
    deletePeople(key) {
      this.service.append(`/${key}.json`).del().execute('peoples')
    },

    // append key.json to url, and set post method. Execute this settings in peoples route with name data to validation
    updatePeople() {
      const {key, name} = this.peopleToUpdate
      this.service.append(`/${key}.json`).put().execute('peoples', {name})
    },

    // this method is called after response rigth from request make by execute method
    serviceSuccess(data) {
      this.load()
    },

    // this method is called after response wrong from request make by execute method
    serviceError(error) {
      alert(error)
    },

    // this method is called why has valitation error, message error is pass in param
    validationError(message) {
      alert(message)
    }
  }
}
</script>

Note the use from helpers methods. See follow they...

Helpers methods

We have some methods to help you!

To execute method, use this methods to define type of request:

  • this.service.get().execute(...) : define GET http method
  • this.service.pos().execute(...) : define POST http method
  • this.service.put().execute(...) : define PUT http method
  • this.service.del().execute(...) : define DELETE http method

To methods execute ou call, use this methods for change url of request:

  • this.service.append('foo').execute(...) : add 'foo' in url request. Result: url + path + 'foo'
  • this.service.append('bar').execute(...) : add 'bar' in url request. Result: url + bar + path

Contributing

To contribute this plugin, fork, edit and send an PR for me. Before send PR, run npm run build to transpile source to ES5.

You might also like...
V-Model is a model plugin for Vue.js, like ng-resource.

V-Model V-Model is a model plugin for Vue.js, like ng-resource. based on axios, path-to-regexp, and bluebird. The V-Model provides interaction support

Async data loading plugin for Vue.js 2.0
Async data loading plugin for Vue.js 2.0

vue-async-data for Vue.js 2.0 Async data loading plugin for Vue.js Install this plugin is written in ES2015, so recommend compile with babel/babel-pol

Stale-while-revalidate data fetching for Vue
Stale-while-revalidate data fetching for Vue

swrv swrv (pronounced "swerve") is a library using the @vue/composition-api for remote data fetching. It is largely a port of swr. Documentation The n

Vue 2 directive to easily add AJAX requests to your application

v-fetch v-fetch is a Vue directive to add AJAX to your app without the boilerplate Summary v-fetch is a directive that adds AJAX functionality to your

A solution to simplify import and use of Vue.js components

vue-import-and-use A solution to simplify import and use of Vue.js components Instalation $ npm install --save vue-import-and-use Without vue-import-a

Webpack loader for extract html in the vue template tag and remove it from bundle js

Vue template extractor Webpack loader for extract html in the vue template tag and remove it from bundle js.

A vue router storage solution. -If your vue application needs to jump to a third party page, and then jump back, want to restore to the original history and continue to operate, the use of this plug-in is the best solution.如果你的vue应用需要跳转到第三方页面,再跳转回来时,想恢复到原来的历史记录并继续操作,使用本插件是最好的解决方案。 Can remove the audio file that the sample rate is less than 44.1 HZ
Can remove the audio file that the sample rate is less than 44.1 HZ

Can remove the audio file that the sample rate is less than 44.1 HZ

A webpack loader i18n solution for Vue (Nuxt) with auto generated keysA webpack loader i18n solution for Vue (Nuxt) with auto generated keys

vue-i18n-loader - another webpack loader i18n solution for Vue (Nuxt) with auto generated keys. Currently under development, pull requests and suggest

Event portal for associations that enables an information flow to the members and to simplify the member and event management

EventPortal Event portal for associations that enables an information flow to the members and to simplify the member and event management. Starting Vu

data table simplify! -- vuetable is a Vue.js component that will automatically request (JSON) data from the server and display them nicely in html table with swappable/extensible pagination component.

Please Note! This is the previous version that works with Vue 1.x. The most up-to-date version is the Vuetable-2. If you like it, please star the Vuet

Vue-Boilerplate - This boilerplate was made to simplify working with Vue

Vue-Boilerplate This boilerplate was made to simplify working with Vue Packages: - Vite - Vue3 - Vue-Router - TypeScript - altv/types-webviews Does al

data table simplify! -- datatable component for Vue 2.x. See documentation at

Vuetable-2 - data table simplify! Vuetable-2 v2.0-beta is available now! See the next branch. Vuetable-2 works with Vue 2.x, vuetable is for Vue 1.x I

Simplify Vue context menu component
Simplify Vue context menu component

vue-easycm 一个简单好用的 VUE 环境菜单 (Context Menu) 更多demo: http://boenfu.github.io/vue-easycm/ 配置简单 自定义程度高 多种引用方式 最高三层菜单 可添加字体图标 边界检测 Install npm install vue-

A utility to simplify the use of REST APIs with Vuex

vuex-rest-api A Helper utility to simplify the usage of REST APIs with Vuex 2. Uses the popular HTTP client axios for requests. Works with websanova/v

Store Organizer To Simplify Your Stores
Store Organizer To Simplify Your Stores

Vue Simple Store Vue Simple Store is a vue plugin which will simplify your App Store. It will combine your separated stores into one global store. let

A utility to simplify the use of REST APIs with Vuex

vuex-rest-api A Helper utility to simplify the usage of REST APIs with Vuex 2. Uses the popular HTTP client axios for requests. Works with websanova/v

Pi-Control 🐱‍👤 is an App for controlling your raspberry pi. It was designed to help with information gathering, as well as to simplify control.

pi-control Preperations (one time) # maybe you need to add 'sudo' for every command, even to start 'pm2' service so it can edit files for example # i

Simplify vuex loading state management

vuex-loading Simplify vuex loading state management Installing Using npm: $ npm install vuex-loadings -s Know Simplify vuex loading state management n

Comments
  • Exemplo Usar com o VIACEP

    Exemplo Usar com o VIACEP

    Nota dez o projeto, gostei muito, se puder passar um exemplo com o VIA CEP ficarei agradecido.

    https://viacep.com.br/ws/01001000/json/

    O parametro '01001000' é o cep e a URL termina com '/json/'

    Obrigado.

    opened by scalarerp 2
Owner
Leonardo Vilarinho
Freelance Full Stack PHP Developer
Leonardo Vilarinho
VueJS RESTful client with reactive features. Vue-Chimera is based on axios http client library.

VueJS RESTful client with reactive features. Vue-Chimera is based on axios http client library.

null 167 Jan 3, 2023
Vue Axios Http - This package helps you quickly to build requests for REST API

Vue Axios Http This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes.

Chantouch Sek 4 Apr 9, 2022
axios plugin for Vuejs project

vue-axios-plugin 简体中文 | English axios plugin for Vuejs project How to install Script tag <!-- add it after vue.js --> <script src="https://unpkg.com/v

Yuga Sun 55 Oct 15, 2022
Smart asynchronous data and computed properties for vue components.

vue-async-properties Vue Component Plugin for asynchronous data and computed properties. A Marketdial Project new Vue({ props: { articleId: Numb

MarketDial 38 Jun 21, 2021
Backend mocking for rapid project testing and previews

Vue-Resource-Mock This package requires no specific version of Vue but vue-resource. It works for both Vue/Vue2 as the time of this writing. Copy and

xiuxiuxiu 29 Nov 1, 2021
💎 Elegant and simple way to build requests for REST API

Elegant and simple way to build requests for REST API This package helps you quickly to build requests for REST API. Move your logic and backend reque

Robson Tenório 1.6k Dec 28, 2022
Hermes is a MITM proxy that allows HTTP, HTTPS and HTTP/2 trafic interception.

Hermes is a man-in-the-middle proxy that allows HTTP, HTTPS and HTTP/2 trafic interception, inspection and modification.

Open-Source by Veepee 29 Nov 10, 2022
⚡️ A request library for Vue 3. 一个能轻松帮你管理请求状态的 Vue 3 请求库。欢迎使用~

English | 简体中文 VueRequest ⚡️ A request library for Vue 3. Status: Beta Features ?? All data is reactive ?? Interval polling ?? Automatic error retry ?

Atto 826 Jan 2, 2023
The HTTP client for Vue.js

vue-resource The plugin for Vue.js provides services for making web requests and handle responses using a XMLHttpRequest or JSONP. Features Supports t

Pagekit 10.1k Dec 30, 2022
Async computed properties for Vue.js

vue-async-computed With this plugin, you can have computed properties in Vue that are computed asynchronously. Without using this plugin, you can't do

Benjamin Fox 1.1k Dec 28, 2022