Product
Introducing Enhanced Alert Actions and Triage Functionality
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
vue-axios-http
Advanced tools
Changelog
1.2.4 (2022-04-08)
Readme
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
BaseProxy
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,
NodeJs, ExpressJs, or any other languages.
Take a look at the usage section to view a detailed example on how to use it.
You can install the package via yarn (or npm):
npm install vue-axios-http
yarn add vue-axios-http
import Vue from 'vue'
import AxiosHttp from 'vue-axios-http'
Vue.use(AxiosHttp)
Put it on top of axios module
export default {
modules: [
// simple usage
'vue-axios-http/nuxt',
// With options
['vue-axios-http/nuxt', { errorProperty: 'errors' }],
'@nuxtjs/axios',
],
axiosHttp: { errorProperty: 'errors' },
}
you can overwrite it, by adding in config above.
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,
},
}
-------------- Todo --------------
import Vue from 'vue'
import AxiosHttp from 'vue-axios-http'
Vue.use(AxiosHttp)
Error response must look like: or base on errorProperty from config
{
"errors": {
"field": ["The field is required."]
}
}
It will create $errors
object inside components.
| 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) | false | 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). |
1.Create proxies folder or your prefer folder name for this
~/proxies/NewsProxy.js
import { BaseProxy } from 'vue-axios-http'
class NewsProxy extends BaseProxy {
constructor(parameters = {}) {
super('news', parameters)
}
}
export default NewsProxy
2.Store
actions.js
import { ALL } from './mutation-types'
import { NewsProxy } from '~/proxies'
import { BaseTransformer, PaginationTransformer } from 'vue-axios-http'
import { pagination, notify } from '~/utils'
const proxy = new NewsProxy()
const all = async ({ commit, dispatch }, payload = {}) => {
const { fn } = payload
if (typeof fn === 'function') {
await fn(proxy)
}
try {
const { data, meta } = await proxy.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: {},
})
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: (proxy) => {
proxy
.setParameters({
userId: id,
include: ['categories'],
})
.removeParameters(['page', 'limit'])
},
})
},
}
mounted()
export default {
mounted() {
const { id = null } = this.$auth.user
this.$store.dispatch('news/all', {
fn: (proxy) => {
proxy
.setParameters({
userId: id,
include: ['categories'],
})
.removeParameters(['page', 'limit'])
},
})
},
}
You can set or remove any parameters you like.
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 |
Set parameters with key/value.
Note: If you to pass query string as object that can be response like object format at api side.
const proxy = new ExampleProxy()
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 } = proxy.setParameters(parameters).all()
this.data = data
Note: 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
const proxy = new ExampleProxy()
const { data } = await proxy.setParameter('page', 1).all()
this.data = data
Expected will be:
{
"page": 1
}
const proxy = new ExampleProxy()
const queryString = 'limit=10&page=1&search[name]=hello'
const { data } = await proxy.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
import { NewsProxy } from '~/proxies'
const proxy = new NewsProxy()
export default {
methods: {
async fetchNews(id) {
try {
const { data } = await proxy.find(id)
this.detail = data
} catch (e) {
console.log(e)
}
},
},
mounted() {
this.fetchNews(this.$route.params.id)
},
}
Can use vue-vlidator
for client-side validator that inspired by Laravel.
Chantouch/vue-vlidator
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 |
<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>
Email: chantouchsek.cs83@gmail.com
Twitter @DevidCs83
FAQs
Elegant and simple way to build requests for REST API
The npm package vue-axios-http receives a total of 89 weekly downloads. As such, vue-axios-http popularity was classified as not popular.
We found that vue-axios-http demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.