Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vue-axios-http

chantouchsek585MIT3.5.0TypeScript support: included

Elegant and simple way to build requests for REST API

vue, nuxt, api, rest, query, builder, laravel, queries, vue-axios, vue api queries, api request

readme

Vue Axios Http

ci Latest Version on NPM Software License npm npm

This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes. Keep your code clean and elegant.

Wouldn't it be great if you could just use your back end to validate forms on the front end? This package provides a BaseService class that does exactly that. It can post itself to a configured endpoint and manage errors. The class is meant to be used with a Laravel back end, and it doesn't limit that you need only to work with laravel, Ruby on Rail, Node.js, Express.js, or any other languages.

Take a look at the usage section to view a detailed example on how to use it.

Install

You can install the package via yarn (or npm):

npm install vue-axios-http
yarn add vue-axios-http

Usage

import Vue from 'vue'
import AxiosHttp from 'vue-axios-http'

Vue.use(AxiosHttp)

Nuxt Support

Put it on top of axios module

export default {
  modules: [
    // simple usage
    'vue-axios-http/nuxt',
    // With options
    ['vue-axios-http/nuxt', { errorProperty: 'errors', resetParameter: true }],
    '@nuxtjs/axios',
  ],
  axiosHttp: { errorProperty: 'errors', resetParameter: true },
}

Options

you can overwrite it by adding in the config above.

Note:

baseURL is required.

You can define baseURL at .env just one of them

API_URL=http://localhost::3000/api
API_HOST=http://localhost::3000/api

if your axios already defined in nuxt.config.js

export default {
  axios: {
    baseURL: process.env.API_URL,
  },
}

Advance usage

-------------- Todo --------------

Vue plugins

import Vue from 'vue'
import AxiosHttp from 'vue-axios-http'

Vue.use(AxiosHttp)

Note

Error response must look like: or based on errorProperty from config

{
  "errors": {
    "field": ["The field is required."]
  }
}

It will create $errors object inside components.

Methods are available:

Validator Description
has(field = null) check specific field error
first(field) get message by field name.
missed(field = null) check if there is no any error of given field name.
nullState(field = null) Check if null of given field.
any() check if any errors exist.
get(field) get specific field.
all() get all errors.
count() get errors count.
fill(errors = {}) fill the errors object.
flush() clear all errors.
clear(field) clear specific error by field name.
onKeydown(event, 'baseFormName') event to clear error by event.target.name. (input the has name).

first(field || fields)

const errors = { name: [{ kh: ['This fist name field is required'] }] }

$errors.first('name') // return array
$errors.first('name[0]') // return object like
$errors.first('name[0].kh') // return string like

$errors.first(['name']) // return array
$errors.first(['name[0]']) // return object like
$errors.first(['name[0].kh']) // return string like

Using it with Vuex

1.Create proxies folder or your prefer folder name for this

~/proxies/NewsService.js

import { BaseService } from 'vue-axios-http'

class NewsService extends BaseService {
  constructor(parameters = {}) {
    super('news', parameters)
  }
}

export default NewsService

2.Store

  • Create news store

  • actions.js

  • getters.js
  • mutation-types.js
  • mutations.js
  • state

actions.js

import { ALL } from './mutation-types'
import { NewsService } from '~/proxies'
import { BaseTransformer, PaginationTransformer } from 'vue-axios-http'
import { pagination, notify } from '~/utils'

const service = new NewsService()

const all = async ({ commit, dispatch }, payload = {}) => {
  const { fn } = payload
  if (typeof fn === 'function') {
    await fn(service)
  }
  try {
    const { data, meta } = await service.all()
    const all = {
      items: BaseTransformer.fetchCollection(data),
      pagination: PaginationTransformer.fetch(meta),
    }
    await commit(ALL, all)
  } catch (e) {
    const data = { items: [], pagination }
    await commit(ALL, data)
    await notify({ response: e })
  }
}

export default {
  all,
}

getters.js

export default {
  all: (state) => state.all,
}

mutation-types.js

export const ALL = 'ALL'

export default { ALL }

mutations.js

import { ALL } from './mutation-types'

export default {
  [ALL](state, payload = {}) {
    const { items = [], pagination = {} } = payload
    state.all = items
    state.pagination = pagination
  },
}

state.js

export default () => ({
  all: [],
  pagination: {},
})

How to call in components or pages

  • news.vue pages

It can be called in mounted() or asyncData()

  • asyncData()
export default {
  async asyncData({ app, store }) {
    const { id = null } = app.$auth.user
    await store.dispatch('news/all', {
      fn: (service) => {
        service
          .setParameters({
            userId: id,
            include: ['categories'],
          })
          .removeParameters(['page', 'limit'])
      },
    })
  },
}
  • mounted()
export default {
  mounted() {
    const { id = null } = this.$auth.user
    this.$store.dispatch('news/all', {
      fn: (service) => {
        service
          .setParameters({
            userId: id,
            include: ['categories'],
          })
          .removeParameters(['page', 'limit'])
      },
    })
  },
}

You can set or remove any parameters you like.

Service methods are available

Method Description
setParameter(key, value) Set param by key and value
removeParameter(key) Remove param by key
setParameters({ key: value, key1: value1 }) Set params by key and value
removeParameters([key1, key2]) Remove params by keys
removeParameters() Remove all params

setParameters()

Set parameters with key/value.

Note: If you to pass query string, as an object that can be response like object format at api side.

Example

const service = new ExampleService()
const parameters = {
  search: {
    first_name: 'Sek',
    last_name: 'Chantouch',
  },
  page: {
    limit: 20,
    offset: 1,
  },
  order: {
    first_name: 'ASC',
    last_name: 'DESC',
  },
  category_id: 6,
}
const { data } = service.setParameters(parameters).all()
this.data = data

Note: A query object above will transform into query string like:

https://my-web-url.com?search[first_name]=Sek&search[last_name]=Chantouch&page[limit]=10&page[offset]=1&order[first_name]=asc&order[last_name]=desc&category_id=6

if setParameter that value is empty or null, it will remove that param for query string

setParameter()

Example 1

const service = new ExampleService()
const { data } = await service.setParameter('page', 1).all()
this.data = data

Expected will be:

{
  "page": 1
}

Example 2

const service = new ExampleService()
const queryString = 'limit=10&page=1&search[name]=hello'
const { data } = await service.setParameter(queryString).all()
this.data = data

Expected will be:

{
  "limit": 10,
  "page": 1,
  "search": {
    "name": "hello"
  }
}

Be sure to use only once in mounted() or asyncData() and asyncData() is only available in NuxtJs

Use service in components

  • news/_id.vue pages
import { NewsService } from '~/proxies'

const service = new NewsService()

export default {
  methods: {
    async fetchNews(id) {
      try {
        const { data } = await service.find(id)
        this.detail = data
      } catch (e) {
        console.log(e)
      }
    },
  },
  mounted() {
    this.fetchNews(this.$route.params.id)
  },
}

Validations

Can use vue-vlidator for client-side validator that inspired by Laravel. Chantouch/vue-vlidator

Errors methods available

It can be called by this.$errors.**

Method Description
all() To get all errors messages
has(attribute) To check an attribute as any error
has(attributes) To check multiple attributes given have any errors
first(attribute) To get errors message by an attribute

How to use in a vue component

<template>
  <v-form v-model="valid" lazy-validation @keydown.native="$errors.onKeydown" @submit.prevent="submit">
    <v-container>
      <v-row>
        <v-col cols="12" md="4">
          <v-text-field
            v-model="firstname"
            :error-messages="$errors.first(['firstname'])"
            :counter="10"
            label="First name"
            required
            name="firstname"
          />
        </v-col>
        <v-col cols="12" md="4">
          <v-text-field
            v-model="lastname"
            :counter="10"
            label="Last name"
            required
            :error-messages="$errors.first(['lastname'])"
          />
        </v-col>
        <v-col cols="12" md="4">
          <v-text-field v-model="email" :counter="10" label="Email" required :error-messages="$errors.first('email')" />
        </v-col>
        <v-col cols="12" md="4">
          <v-text-field v-model="email" label="E-mail" required />
        </v-col>
      </v-row>
    </v-container>
  </v-form>
</template>
<script>
export default {
  data: () => ({
    valid: false,
    firstname: '',
    lastname: '',
    email: '',
  }),
  methods: {
    submit() {
      this.$axios.$post('/account/create', {
        firstname: this.firstname,
        lastname: this.lastname,
        email: this.email,
      })
    },
  },
  beforeDestroy() {
    this.$errors.flush()
  },
}
</script>

Contact

Email: chantouchsek.cs83@gmail.com

Twitter @DevidCs83

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

3.5.0 (2024-05-08)

Features

  • migrate eslint flat config (cdc159c)

Bug Fixes

  • correct husky config (d6cc229)
  • deps: bump actions/checkout from 4.1.4 to 4.1.5 (96e7d77)
  • types (cb599ca)

3.4.1 (2024-04-30)

Bug Fixes

  • :label: cast types and fix ternary condition (70c0451)

3.4.0 (2024-04-30)

Features

  • :sparkles: add support wildcard fields (1eefc70)

Bug Fixes

  • :lock: replace by lodash (8c57402)
  • deps: bump @babel/traverse from 7.20.13 to 7.23.2 (2a0b40c)
  • deps: bump actions/checkout from 4.1.0 to 4.1.1 (0bb8a34)
  • deps: bump actions/checkout from 4.1.1 to 4.1.4 (46ca987)
  • deps: bump actions/setup-node from 3.8.1 to 4.0.0 (b7d3f91)
  • deps: bump browserify-sign from 4.2.1 to 4.2.2 (297c8d7)
  • deps: bump follow-redirects from 1.15.2 to 1.15.4 (bc837a4)
  • deps: bump follow-redirects from 1.15.4 to 1.15.6 (f3590a0)
  • deps: bump get-func-name from 2.0.0 to 2.0.2 (e52a9e8)
  • deps: bump ip from 1.1.8 to 1.1.9 (20846a7)
  • deps: bump tar from 6.1.13 to 6.2.1 (5ce2d8a)
  • deps: bump webpack-dev-middleware from 5.3.3 to 5.3.4 (bcf3ee6)
  • skip lip check on build (1d3fca8)

3.3.3 (2023-09-27)

Bug Fixes

  • :bug: remove object return types from first function (5fdfe01)

3.3.2 (2023-09-26)

Bug Fixes

  • :bug: encode url param (f120618)
  • deps: bump actions/checkout from 3.5.2 to 3.5.3 (8458d7d)
  • deps: bump actions/checkout from 3.5.3 to 4.1.0 (f8fbea2)
  • deps: bump actions/setup-node from 3.6.0 to 3.7.0 (275ff69)
  • deps: bump actions/setup-node from 3.7.0 to 3.8.1 (e7b1fd6)
  • deps: bump semver from 5.7.1 to 5.7.2 (e2dde20)
  • deps: bump tough-cookie from 4.1.2 to 4.1.3 (1cb4ed4)

3.3.1 (2023-05-24)

Bug Fixes

  • :bug: accept all options from nuxt config (ffa539a)
  • deps-dev: bump @vitest/coverage-c8 from 0.28.4 to 0.31.1 (9ec905b)
  • spread options by string (e443ba2)

3.3.0 (2023-05-18)

Features

  • :sparkles: add remove param option (267afba)
  • :tada: optimize some logic of util (ad4fd10)

Bug Fixes

  • :bug: correty default value of parameters (9fc25a1)
  • :pencil2: fix the typos (39e989c)
  • :penicil2: rename the property (76bdf91)
  • :poop: remove the test (505bf94)
  • deps: bump actions/checkout from 3.3.0 to 3.5.2 (868c4b2)
  • deps: bump actions/stale from 7 to 8 (a5ea951)
  • deps: bump axios from 0.27.2 to 1.3.0 (cb065a4)
  • deps: bump qs from 6.11.0 to 6.11.2 (c9eaba9)

3.2.1 (2023-01-26)

Bug Fixes

  • :bug: change export order (0863b39)
  • :bug: make form as any type and added new method (2b7f45f)
  • :bug: remove type-fest (5f048e9)
  • :bug: removed checking method type (5f87c91)
  • :fire: renamed property (9dcb639)
  • :pencil2: inline and make some code (6ff84d1)
  • :pencil2: remove not used function (64510d0)
  • deps: update lock file (f4fe511)
  • fire: removed unused method (f55988a)

3.2.0 (2023-01-25)

Features

  • :sparkles: clear the field and get any (e3576c4)
  • :sparkles: get multiple field by camel or snake case (b22aae0)

Bug Fixes

  • :bug: remove the return type annotataion (ce1031e)
  • deps: bump actions/checkout from 3.1.0 to 3.3.0 (cb1ec39)
  • deps: bump actions/setup-node from 3.5.0 to 3.5.1 (c998da5)
  • deps: bump actions/setup-node from 3.5.1 to 3.6.0 (3629f0b)
  • deps: bump actions/stale from 6 to 7 (8043b4a)
  • deps: bump decode-uri-component from 0.2.0 to 0.2.2 (94672bc)
  • deps: bump json5 from 1.0.1 to 1.0.2 (6d82afd)
  • deps: bump loader-utils from 1.4.0 to 1.4.1 (c10208e)
  • deps: bump loader-utils from 1.4.1 to 1.4.2 (7deeccc)
  • deps: bump ua-parser-js from 1.0.2 to 1.0.33 (d2f0dd1)
  • deps: using nuxt instead (b3c3e7d)
  • test: test coverage (ba7d69e)

3.1.3 (2022-10-12)

Bug Fixes

  • added force update to add function (260968d)
  • deps: bump actions/checkout from 3.0.2 to 3.1.0 (43cd574)
  • deps: bump actions/setup-node from 3.3.0 to 3.4.0 (faeb861)
  • deps: bump actions/setup-node from 3.4.0 to 3.4.1 (abd4b49)
  • deps: bump actions/setup-node from 3.4.1 to 3.5.0 (8a62e57)
  • deps: bump actions/stale from 5 to 6 (e6695e7)
  • deps: bump terser from 4.8.0 to 4.8.1 (1e0203a)

3.1.2 (2022-07-08)

Bug Fixes

  • :tada: make the clear fuction onkeydown work correctly (1b9a550)
  • make keydown more specific (045be20)
  • remove unused type (ad383b7)
  • typing typo (29def5b)

3.1.1 (2022-07-08)

Bug Fixes

  • :fire: make fill method print the same the value from api (ddb6b08)
  • deps: bump parse-url from 6.0.0 to 6.0.2 (3e71ffb)
  • deps: bump qs from 6.10.5 to 6.11.0 (5ebc28f)
  • deps: bump shell-quote from 1.7.2 to 1.7.3 (db6a556)

3.1.0 (2022-06-19)

Features

  • add deep array access for first() (9223a7b)

Bug Fixes

  • deps: bump actions/setup-node from 3.2.0 to 3.3.0 (aa39996)
  • deps: bump qs from 6.10.3 to 6.10.5 (7e19a9b)
  • update readme (068238b)
  • update readme (afeaf69)
  • update readme (a47a8fc)

3.0.1 (2022-05-25)

Bug Fixes

  • :beer: make type of axios error (a7b6f9d)
  • :fire: fix data type wrong (56d343b)
  • :fire: fix put and path method with only payload (9b324f5)
  • deps: bump actions/checkout from 3.0.1 to 3.0.2 (a5654c9)
  • deps: bump actions/setup-node from 3.1.1 to 3.2.0 (90ac179)
  • deps: bump github/codeql-action from 1 to 2 (e153058)
  • remove check file in puth method (d1d0173)
  • remove type (3cf6170)

3.0.0 (2022-04-19)

⚠ BREAKING CHANGES

  • renamed all proxy to service
  • :fire: rename BaseProxy class to BaseService class
  • break: remove unused methods
  • methods: remvoe redundant methods from base proxy class

Features

  • add more options to methods (66de43c)

Bug Fixes

  • check set remove param method (e8f3cf4)
  • make paraeter type to be object type (129b46d)
  • :fire: rename BaseProxy class to BaseService class (1e486c3)
  • break: remove unused methods (47f65cb)
  • methods: remvoe redundant methods from base proxy class (4fb5adb)
  • renamed all proxy to service (a69a5ba)

2.0.1 (2022-04-19)

Bug Fixes

  • :fire: remove readonly from endpoint property (8f6f8e7)
  • deps: bump actions/checkout from 3.0.0 to 3.0.1 (dd8e124)
  • deps: bump actions/setup-node from 3.1.0 to 3.1.1 (58d0d0a)
  • deps: bump actions/stale from 4 to 5 (32a293d)

2.0.0 (2022-04-09)

⚠ BREAKING CHANGES

  • deps: remove transformers and snackcase and camelcase keys

  • deps: remove transformers and snackcase and camelcase keys (260dfa1)

1.3.0 (2022-04-09)

Features

  • :tada: added new method putWithoutId to base service (8a9e0c2)

1.2.5 (2022-04-09)

Bug Fixes

  • :beer: allow more http methods (a1aac4d)

1.2.4 (2022-04-08)

Bug Fixes

  • deps: bump actions/checkout from 2.4.0 to 3.0.0 (76108e6)
  • deps: bump actions/setup-node from 2.5.1 to 3.1.0 (907bd7e)
  • deps: bump camelcase-keys from 7.0.1 to 7.0.2 (3b7293d)
  • deps: bump follow-redirects from 1.14.6 to 1.14.7 (24c86c8)
  • deps: bump follow-redirects from 1.14.7 to 1.14.8 (2b2a457)
  • deps: bump minimist from 1.2.5 to 1.2.6 (8abaf7d)
  • deps: bump nanoid from 3.1.28 to 3.2.0 (cb3d4c8)
  • deps: bump node-fetch from 2.6.5 to 2.6.7 (e37e9db)
  • deps: bump qs from 6.10.2 to 6.10.3 (d573f28)
  • deps: bump snakecase-keys from 5.1.2 to 5.4.0 (f195b47)

1.2.3 (2022-01-10)

Bug Fixes

  • :beer: fix return correct type of base service and add lint staged (3dd7501)

1.2.2 (2022-01-04)

Bug Fixes

  • :fire: renamed git repository name (a7682cd)
  • deps: bump actions/setup-node from 2.4.1 to 2.5.1 (838f53f)
  • downgrade tsconfig target to es2019 (bd3050f)
  • lintfix codeql (2d387e6)
  • ran lintfix style (a8849fa)

1.2.1 (2021-10-02)

Bug Fixes

  • prevent transform on undefined or null and set default response data (47071fa)

1.2.0 (2021-10-02)

Features

  • :rocket: added is plain object function helpers (7b3ebff)
  • :tada: added axios duplicate blocker check the request (87c25c0)
  • :tada: added new first by method validator class (ddb84f7)

Bug Fixes

  • deps: bump actions/setup-node from 2.4.0 to 2.4.1 (0bd0fb3)
  • test: :white_check_mark: fixed and update some types (79a5e50)