{"id":20393531,"url":"https://github.com/chantouchsek/vue-axios-http","last_synced_at":"2025-04-12T12:05:51.887Z","repository":{"id":36984246,"uuid":"299025409","full_name":"chantouchsek/vue-axios-http","owner":"chantouchsek","description":"Elegant and simple way to build requests for REST API","archived":false,"fork":false,"pushed_at":"2025-03-25T02:17:37.000Z","size":6427,"stargazers_count":6,"open_issues_count":12,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-26T06:43:32.194Z","etag":null,"topics":["api","laravel","pagination","queries","query","vue","vue-api","vue-axios","vue-request","vuex"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chantouchsek.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"patreon":"chantouch"}},"created_at":"2020-09-27T12:17:44.000Z","updated_at":"2024-12-11T02:50:00.000Z","dependencies_parsed_at":"2024-03-24T15:30:11.859Z","dependency_job_id":"4dc98213-1fbe-4d47-864f-370f90667d50","html_url":"https://github.com/chantouchsek/vue-axios-http","commit_stats":{"total_commits":441,"total_committers":5,"mean_commits":88.2,"dds":"0.43083900226757366","last_synced_commit":"78f4dbc290e8bde8aa772f0e3a935dd829df622f"},"previous_names":["chantouchsek/vue-api-queries"],"tags_count":44,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvue-axios-http","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvue-axios-http/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvue-axios-http/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvue-axios-http/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chantouchsek","download_url":"https://codeload.github.com/chantouchsek/vue-axios-http/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248565061,"owners_count":21125415,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","laravel","pagination","queries","query","vue","vue-api","vue-axios","vue-request","vuex"],"created_at":"2024-11-15T03:49:12.572Z","updated_at":"2025-04-12T12:05:51.869Z","avatar_url":"https://github.com/chantouchsek.png","language":"TypeScript","funding_links":["https://patreon.com/chantouch"],"categories":[],"sub_categories":[],"readme":"# Vue Axios Http\n\n[![ci](https://github.com/chantouchsek/vue-axios-http/actions/workflows/ci.yml/badge.svg)](https://github.com/chantouchsek/vue-axios-http/actions/workflows/ci.yml)\n[![Latest Version on NPM](https://img.shields.io/npm/v/vue-axios-http.svg?style=flat-square)](https://npmjs.com/package/vue-axios-http)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)\n[![npm](https://img.shields.io/npm/dt/vue-axios-http.svg?style=flat-square)](https://npmjs.com/package/vue-axios-http)\n[![npm](https://img.shields.io/npm/dm/vue-axios-http.svg?style=flat-square)](https://npmjs.com/package/vue-axios-http)\n\nThis package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated\nclasses. Keep your code clean and elegant.\n\nWouldn't it be great if you could just use your back end to validate forms on the front end? This package provides a\n`BaseService` class that does exactly that. It can post itself to a configured endpoint and manage errors. The class is\nmeant to be used with a Laravel back end, and it doesn't limit that you need only to work with laravel, Ruby on Rail,\nNode.js, Express.js, or any other languages.\n\nTake a look at the [usage section](#usage) to view a detailed example on how to use it.\n\n## Install\n\nYou can install the package via yarn (or npm):\n\n```npm\nnpm install vue-axios-http\n```\n\n```yarn\nyarn add vue-axios-http\n```\n\n## Usage\n\n```js\nimport Vue from 'vue'\nimport AxiosHttp from 'vue-axios-http'\n\nVue.use(AxiosHttp)\n```\n\n## Nuxt Support\n\nPut it on top of axios module\n\n```js\nexport default {\n  modules: [\n    // simple usage\n    'vue-axios-http/nuxt',\n    // With options\n    ['vue-axios-http/nuxt', { errorProperty: 'errors', resetParameter: true }],\n    '@nuxtjs/axios',\n  ],\n  axiosHttp: { errorProperty: 'errors', resetParameter: true },\n}\n```\n\n### Options\n\nyou can overwrite it by adding in the config above.\n\n### Note:\n\n`baseURL` is required.\n\nYou can define `baseURL` at .env just one of them\n\n```bash\nAPI_URL=http://localhost::3000/api\nAPI_HOST=http://localhost::3000/api\n```\n\nif your axios already defined in `nuxt.config.js`\n\n```js\nexport default {\n  axios: {\n    baseURL: process.env.API_URL,\n  },\n}\n```\n\n### Advance usage\n\n-------------- Todo --------------\n\n### Vue plugins\n\n```js\nimport Vue from 'vue'\nimport AxiosHttp from 'vue-axios-http'\n\nVue.use(AxiosHttp)\n```\n\n### Note\n\nError response must look like: or based on **errorProperty** from config\n\n```json\n{\n  \"errors\": {\n    \"field\": [\"The field is required.\"]\n  }\n}\n```\n\nIt will create `$errors` object inside components.\n\n## Methods are available:\n\n| Validator                            | Description                                                      |\n| ------------------------------------ | ---------------------------------------------------------------- |\n| **has(field = null)**                | check specific field error                                       |\n| **first(field)**                     | get message by field name.                                       |\n| **missed(field = null)**             | check if there is no any error of given field name.              |\n| **nullState(field = null)**          | Check if null of given field.                                    |\n| **any()**                            | check if any errors exist.                                       |\n| **get(field)**                       | get specific field.                                              |\n| **all()**                            | get all errors.                                                  |\n| **count()**                          | get errors count.                                                |\n| **fill(errors = {})**                | fill the errors object.                                          |\n| **flush()**                          | clear all errors.                                                |\n| **clear(field)**                     | clear specific error by field name.                              |\n| **onKeydown(event, 'baseFormName')** | event to clear error by event.target.name. (input the has name). |\n\n#### first(field || fields)\n\n```js\nconst errors = { name: [{ kh: ['This fist name field is required'] }] }\n\n$errors.first('name') // return array\n$errors.first('name[0]') // return object like\n$errors.first('name[0].kh') // return string like\n\n$errors.first(['name']) // return array\n$errors.first(['name[0]']) // return object like\n$errors.first(['name[0].kh']) // return string like\n```\n\n## Using it with Vuex\n\n1.Create **proxies** folder or your prefer folder name for this\n\n`~/proxies/NewsService.js`\n\n```js\nimport { BaseService } from 'vue-axios-http'\n\nclass NewsService extends BaseService {\n  constructor(parameters = {}) {\n    super('news', parameters)\n  }\n}\n\nexport default NewsService\n```\n\n2.Store\n\n- Create news store\n\n1. actions.js\n2. getters.js\n3. mutation-types.js\n4. mutations.js\n5. state\n\n---\n\nactions.js\n\n```js\nimport { ALL } from './mutation-types'\nimport { NewsService } from '~/proxies'\nimport { BaseTransformer, PaginationTransformer } from 'vue-axios-http'\nimport { pagination, notify } from '~/utils'\n\nconst service = new NewsService()\n\nconst all = async ({ commit, dispatch }, payload = {}) =\u003e {\n  const { fn } = payload\n  if (typeof fn === 'function') {\n    await fn(service)\n  }\n  try {\n    const { data, meta } = await service.all()\n    const all = {\n      items: BaseTransformer.fetchCollection(data),\n      pagination: PaginationTransformer.fetch(meta),\n    }\n    await commit(ALL, all)\n  } catch (e) {\n    const data = { items: [], pagination }\n    await commit(ALL, data)\n    await notify({ response: e })\n  }\n}\n\nexport default {\n  all,\n}\n```\n\n---\n\ngetters.js\n\n```js\nexport default {\n  all: (state) =\u003e state.all,\n}\n```\n\n---\n\nmutation-types.js\n\n```js\nexport const ALL = 'ALL'\n\nexport default { ALL }\n```\n\n---\n\nmutations.js\n\n```js\nimport { ALL } from './mutation-types'\n\nexport default {\n  [ALL](state, payload = {}) {\n    const { items = [], pagination = {} } = payload\n    state.all = items\n    state.pagination = pagination\n  },\n}\n```\n\n---\n\nstate.js\n\n```js\nexport default () =\u003e ({\n  all: [],\n  pagination: {},\n})\n```\n\n## How to call in components or pages\n\n- news.vue pages\n\nIt can be called in `mounted()` or `asyncData()`\n\n- `asyncData()`\n\n```js\nexport default {\n  async asyncData({ app, store }) {\n    const { id = null } = app.$auth.user\n    await store.dispatch('news/all', {\n      fn: (service) =\u003e {\n        service\n          .setParameters({\n            userId: id,\n            include: ['categories'],\n          })\n          .removeParameters(['page', 'limit'])\n      },\n    })\n  },\n}\n```\n\n- `mounted()`\n\n```js\nexport default {\n  mounted() {\n    const { id = null } = this.$auth.user\n    this.$store.dispatch('news/all', {\n      fn: (service) =\u003e {\n        service\n          .setParameters({\n            userId: id,\n            include: ['categories'],\n          })\n          .removeParameters(['page', 'limit'])\n      },\n    })\n  },\n}\n```\n\nYou can set or remove any parameters you like.\n\n## Service methods are available\n\n| Method                                          | Description                 |\n| ----------------------------------------------- | --------------------------- |\n| **setParameter(key, value)**                    | Set param by key and value  |\n| **removeParameter(key)**                        | Remove param by key         |\n| **setParameters({ key: value, key1: value1 })** | Set params by key and value |\n| **removeParameters([key1, key2])**              | Remove params by keys       |\n| **removeParameters()**                          | Remove all params           |\n\n#### setParameters()\n\nSet parameters with key/value.\n\n**Note**: If you to pass query string, as an object that can be response like object format at api side.\n\n#### Example\n\n```js\nconst service = new ExampleService()\nconst parameters = {\n  search: {\n    first_name: 'Sek',\n    last_name: 'Chantouch',\n  },\n  page: {\n    limit: 20,\n    offset: 1,\n  },\n  order: {\n    first_name: 'ASC',\n    last_name: 'DESC',\n  },\n  category_id: 6,\n}\nconst { data } = service.setParameters(parameters).all()\nthis.data = data\n```\n\n**Note**: A query object above will transform into query string like:\n\n```text\nhttps://my-web-url.com?search[first_name]=Sek\u0026search[last_name]=Chantouch\u0026page[limit]=10\u0026page[offset]=1\u0026order[first_name]=asc\u0026order[last_name]=desc\u0026category_id=6\n```\n\nif setParameter that value is empty or null, it will remove that param for query string\n\n#### setParameter()\n\n#### Example 1\n\n```js\nconst service = new ExampleService()\nconst { data } = await service.setParameter('page', 1).all()\nthis.data = data\n```\n\nExpected will be:\n\n```json\n{\n  \"page\": 1\n}\n```\n\n#### Example 2\n\n```js\nconst service = new ExampleService()\nconst queryString = 'limit=10\u0026page=1\u0026search[name]=hello'\nconst { data } = await service.setParameter(queryString).all()\nthis.data = data\n```\n\nExpected will be:\n\n```json\n{\n  \"limit\": 10,\n  \"page\": 1,\n  \"search\": {\n    \"name\": \"hello\"\n  }\n}\n```\n\nBe sure to use only once in `mounted()` or `asyncData()` and `asyncData()` is only available in `NuxtJs`\n\n## Use service in components\n\n- news/\\_id.vue pages\n\n```js\nimport { NewsService } from '~/proxies'\n\nconst service = new NewsService()\n\nexport default {\n  methods: {\n    async fetchNews(id) {\n      try {\n        const { data } = await service.find(id)\n        this.detail = data\n      } catch (e) {\n        console.log(e)\n      }\n    },\n  },\n  mounted() {\n    this.fetchNews(this.$route.params.id)\n  },\n}\n```\n\n## Validations\n\nCan use `vue-vlidator` for client-side validator that inspired by Laravel.\n[Chantouch/vue-vlidator](https://github.com/Chantouch/vue-vlidator)\n\n### Errors methods available\n\nIt can be called by `this.$errors.**`\n\n| Method               | Description                                        |\n| -------------------- | -------------------------------------------------- |\n| **all()**            | To get all errors messages                         |\n| **has(attribute)**   | To check an attribute as any error                 |\n| **has(attributes)**  | To check multiple attributes given have any errors |\n| **first(attribute)** | To get errors message by an attribute              |\n\n## How to use in a vue component\n\n```vue\n\u003ctemplate\u003e\n  \u003cv-form v-model=\"valid\" lazy-validation @keydown.native=\"$errors.onKeydown\" @submit.prevent=\"submit\"\u003e\n    \u003cv-container\u003e\n      \u003cv-row\u003e\n        \u003cv-col cols=\"12\" md=\"4\"\u003e\n          \u003cv-text-field\n            v-model=\"firstname\"\n            :error-messages=\"$errors.first(['firstname'])\"\n            :counter=\"10\"\n            label=\"First name\"\n            required\n            name=\"firstname\"\n          /\u003e\n        \u003c/v-col\u003e\n        \u003cv-col cols=\"12\" md=\"4\"\u003e\n          \u003cv-text-field\n            v-model=\"lastname\"\n            :counter=\"10\"\n            label=\"Last name\"\n            required\n            :error-messages=\"$errors.first(['lastname'])\"\n          /\u003e\n        \u003c/v-col\u003e\n        \u003cv-col cols=\"12\" md=\"4\"\u003e\n          \u003cv-text-field v-model=\"email\" :counter=\"10\" label=\"Email\" required :error-messages=\"$errors.first('email')\" /\u003e\n        \u003c/v-col\u003e\n        \u003cv-col cols=\"12\" md=\"4\"\u003e\n          \u003cv-text-field v-model=\"email\" label=\"E-mail\" required /\u003e\n        \u003c/v-col\u003e\n      \u003c/v-row\u003e\n    \u003c/v-container\u003e\n  \u003c/v-form\u003e\n\u003c/template\u003e\n\u003cscript\u003e\nexport default {\n  data: () =\u003e ({\n    valid: false,\n    firstname: '',\n    lastname: '',\n    email: '',\n  }),\n  methods: {\n    submit() {\n      this.$axios.$post('/account/create', {\n        firstname: this.firstname,\n        lastname: this.lastname,\n        email: this.email,\n      })\n    },\n  },\n  beforeDestroy() {\n    this.$errors.flush()\n  },\n}\n\u003c/script\u003e\n```\n\n# Contact\n\nEmail: chantouchsek.cs83@gmail.com\n\nTwitter [@DevidCs83](https://twitter.com/DevidCs83)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchantouchsek%2Fvue-axios-http","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchantouchsek%2Fvue-axios-http","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchantouchsek%2Fvue-axios-http/lists"}