Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Elegant and simple way to build requests for REST API

License

NotificationsYou must be signed in to change notification settings

chantouchsek/vue-axios-http

Repository files navigation

ciLatest Version on NPMSoftware Licensenpmnpm

This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicatedclasses. 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 aBaseService class that does exactly that. It can post itself to a configured endpoint and manage errors. The class ismeant 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 theusage 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

importVuefrom'vue'importAxiosHttpfrom'vue-axios-http'Vue.use(AxiosHttp)

Nuxt Support

Put it on top of axios module

exportdefault{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 definebaseURL at .env just one of them

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

if your axios already defined innuxt.config.js

exportdefault{axios:{baseURL:process.env.API_URL,},}

Advance usage

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

Vue plugins

importVuefrom'vue'importAxiosHttpfrom'vue-axios-http'Vue.use(AxiosHttp)

Note

Error response must look like: or based onerrorProperty from config

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

It will create$errors object inside components.

Methods are available:

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

consterrors={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.Createproxies folder or your prefer folder name for this

~/proxies/NewsService.js

import{BaseService}from'vue-axios-http'classNewsServiceextendsBaseService{constructor(parameters={}){super('news',parameters)}}exportdefaultNewsService

2.Store

  • Create news store
  1. actions.js
  2. getters.js
  3. mutation-types.js
  4. mutations.js
  5. state

actions.js

import{ALL}from'./mutation-types'import{NewsService}from'~/proxies'import{BaseTransformer,PaginationTransformer}from'vue-axios-http'import{pagination,notify}from'~/utils'constservice=newNewsService()constall=async({ commit, dispatch},payload={})=>{const{ fn}=payloadif(typeoffn==='function'){awaitfn(service)}try{const{ data, meta}=awaitservice.all()constall={items:BaseTransformer.fetchCollection(data),pagination:PaginationTransformer.fetch(meta),}awaitcommit(ALL,all)}catch(e){constdata={items:[], pagination}awaitcommit(ALL,data)awaitnotify({response:e})}}exportdefault{  all,}

getters.js

exportdefault{all:(state)=>state.all,}

mutation-types.js

exportconstALL='ALL'exportdefault{ALL}

mutations.js

import{ALL}from'./mutation-types'exportdefault{[ALL](state,payload={}){const{ items=[], pagination={}}=payloadstate.all=itemsstate.pagination=pagination},}

state.js

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

How to call in components or pages

  • news.vue pages

It can be called inmounted() orasyncData()

  • asyncData()
exportdefault{asyncasyncData({ app, store}){const{ id=null}=app.$auth.userawaitstore.dispatch('news/all',{fn:(service)=>{service.setParameters({userId:id,include:['categories'],}).removeParameters(['page','limit'])},})},}
  • mounted()
exportdefault{mounted(){const{ id=null}=this.$auth.userthis.$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

MethodDescription
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

constservice=newExampleService()constparameters={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

constservice=newExampleService()const{ data}=awaitservice.setParameter('page',1).all()this.data=data

Expected will be:

{"page":1}

Example 2

constservice=newExampleService()constqueryString='limit=10&page=1&search[name]=hello'const{ data}=awaitservice.setParameter(queryString).all()this.data=data

Expected will be:

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

Be sure to use only once inmounted() orasyncData() andasyncData() is only available inNuxtJs

Use service in components

  • news/_id.vue pages
import{NewsService}from'~/proxies'constservice=newNewsService()exportdefault{methods:{asyncfetchNews(id){try{const{ data}=awaitservice.find(id)this.detail=data}catch(e){console.log(e)}},},mounted(){this.fetchNews(this.$route.params.id)},}

Validations

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

Errors methods available

It can be called bythis.$errors.**

MethodDescription
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-formv-model="valid"lazy-validation@keydown.native="$errors.onKeydown"@submit.prevent="submit">    <v-container>      <v-row>        <v-colcols="12"md="4">          <v-text-fieldv-model="firstname":error-messages="$errors.first(['firstname'])":counter="10"label="First name"requiredname="firstname"          />        </v-col>        <v-colcols="12"md="4">          <v-text-fieldv-model="lastname":counter="10"label="Last name"required:error-messages="$errors.first(['lastname'])"          />        </v-col>        <v-colcols="12"md="4">          <v-text-fieldv-model="email":counter="10"label="Email"required:error-messages="$errors.first('email')" />        </v-col>        <v-colcols="12"md="4">          <v-text-fieldv-model="email"label="E-mail"required />        </v-col>      </v-row>    </v-container>  </v-form></template><script>exportdefault {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

About

Elegant and simple way to build requests for REST API

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors4

    •  
    •  
    •  
    •  

    [8]ページ先頭

    ©2009-2025 Movatter.jp