0.1.2 • Published 2 years ago

nuxt-form-helper v0.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Repo link Repo link

Nuxt badge

NuxtFormHelper

A Nuxt form helper based on Inertia.js's form helper

Before you start

You must know:

  • This is my first ever module.
  • This module is still under construction.
  • If you see room for improvement, feel free to open a PR.
    • GitHub remains private until test environment is added and stable

Future plans:

  • Make the helper class based.
  • Add ability to test into repo. (Currently being tested in active project)
  • Add a form remember feature using Vue-X store.
  • Learn TypeScript.
  • Convert the module to TypeScript.

Requirements

  • Nuxt 2 (tested on nitro/bridge) and Vue 2
  • Axios: 0.22.0 or higher
  • Lodash: 1.0.0 or higher

Installation

Install the package:

yarn add nuxt-form-helper # or npm install

Usage

1. Register nuxt-form-helper module in your Nuxt application

export default {
  // ...
  modules: [
    // Must be above @nuxtjs/axios since it's depending on it
    'nuxt-form-helper',
    // ...
  ]

  // defaults
  nuxtFormHelper: {
    keyName: 'nuxtForm', // The key to create a form
    parsers: ['laravel', 'custom'], // Default parsers available: laravel, jsonapi
    defaultParser: 'laravel',
    customParsers: {
      // Add your custom parsers here
      custom: '@/parsers/customParser'
    }
  }
  // ...
}

2. Use the helper

In this example I've created a simple form that makes use of the helper abilities.

<template>
  <!-- Basic form example -->
  <form @submit.prevent="onSubmit" style="display: flex; flex-direction: column; flex-wrap: wrap;">
    <label>Username</label>
    <input v-model="form.username" type="text" />
    <small v-if="form.errors.username" v-text="form.errors.username"/>
    <label>First name</label>
    <input v-model="form.first_name" type="text" />
    <small v-if="form.errors.first_name" v-text="form.errors.first_name"/>
    <label>Last name</label>
    <input v-model="form.last_name" type="text" />
    <small v-if="form.errors.last_name" v-text="form.errors.last_name"/>
    <div>
      <input id="terms" v-model="form.agree" type="checkbox">
      <label for="terms">Agree with terms & services</label>
    </div>
    <input type="submit">
  </form>
</template>

<script>
export default {
  data() {
    return {
      // Create a form using the helper
      form: this.$nuxtForm({
        username: '',
        first_name: '',
        last_name: '',
        agree: false,
        value_with_default: 'Default value',
      })
    }
  },
  methods: {
    onSubmit() {
      // Execute request
      this.form.post('api/register', {
        onSuccess: function (data, response) {
          // !!! Example code !!!
          this.$toast({ type: 'success', message: 'Account created!' })
          this.$router.push({ name: 'verify' })
        },
        onError: function (messages, error) {
          // !!! Example code !!!
          // Vee validate example
          this.$refs.form.setErrors(messages)
        }
      })
    }
  }
}
</script>

In this example I query data to show on the page using async asyncData():

<script>
export default {
  async asyncData({ $nuxtForm, params, redirect }) {
    const items = await $nuxtForm().get('api/categories', {
      category: params.category,
      onError: (_, error) => {
        // Go to create if not exist
        if(error?.response?.status === 404) {
          redirect({ name: 'categories-create' })
        }
      }
    })

    return {
      items
    }
  }
}
</script>

Configuration

Nuxt config options

Option nametypeDefaultDescription
keyNameStringnuxtFormThe name of the key to access the helper. Example: value 'test' means you would access the helper by this.$test.
parsersArray['laravel']Array of parsers that should be loaded into the project. You may not need a loader, so if you exclude it from this array it won't be loaded.
defaultParserString'laravel'Name of the loader that should be used when none is specified in form options.
customParsersObject-Object where you can define custom parsers. Their keys may not contain any special chars or whitespace.

Helper options

Options you can pass when defining a form.

form: this.$nuxtForm({
  // Form data props...
}, {
  // Here
})
Option nametypeDescription
axiosObjectCustom Axios options for this specific form.
parserStringUse this form option if you have multiple parsers loaded and you would like to use a different parser for this form than the one than the configured.

Form methods

Methods you can use to manipulate the form. | Method name | Description | Example | | ----------- | ----------- | ------- | | reset(..fields) | Will reset one specific or multiple field(s) to their originally defined value. | reset() or reset('username', 'password') | | setError(key, value) | Allows you to push an error into the form.errors object. | setError('username', "I don't like it, pick another") | | clearErrors(...fields) | Will remove the error from the errors object for one specific or multiple field(s). | clearErrors() or clearErrors('username', 'password') |

Form props

Dynamic real time props that tell the status of the form. | Prop name | Description | | --------- | ----------- | | isDirty | Tells you if the form data has been modified | | errors | Object where you'll find parsed errors | | hasErrors | Tells you if the form has any errors in the errros object | | processing | Tells you if the form is processing. Usefull for when you want to disable buttons when processing. | | progress | Contains the live events from onUploadProgress | | wasSuccessful | Tells you if the form was successful | | recentlySuccessful | Tells you if the form was recently successful (the past 2 seconds) |

Request methods

Methods you can use to execute a request. | Method name | Description | | ----------- | ----------- | | get(url, options) | Submits the form using a GET request | | post(url, options) | Submits the form using a POST request | | put(url, options) | Submits the form using a PUT request | | patch(url, options) | Submits the form using a PATCH request | | delete(url, options) | Submits the form using a DELETE request | | cancel() | Cancels the last from request |

Request callbacks

Callbacks that can be configured in the request method options. | Callback name | Params | Description | | ------------- | ------ | ----------- | | onBefore | options | Fires before the request is made | | onProgress | event (from onUploadProgress) | Fires every Axios onUploadProgress (see in config) and passes the event. | | onSuccess | data (parsed), response (raw) | Fires when a request is made succesfully. | | onCancel | - | Fires when a request cancelled. | | onError | messages (parsed), error (raw) | Fires when a request has failed. | | onFinish | data (parsed), response (raw) | Fires when a request has finished. |

Axios options

Axios options can be set in the parser or passed to the form options and request options respectively. Available options can be found here.

for example:

// In data
return {
  form: this.$nuxtForm({
    // Form data...
  }, {
    axios: {
      // Here
      // Overwrites: parser
    }
  })
}

// In context
this.form.post('/example', {
  axios: {
    // Here
    // Overwrites: parser, form
  }
})

Parsers

Default parsers

I've added 2 default parsers: 1. Laravel 2. JSON:API (Laravel JSON:API)

JSON:API - options

Because JSON:API follows a specifcation there are some options you can use for making querying data easier.

OptionTypeDescriptionExample
extractDataBooleanBy default the parser automatically extracts the data from the response. (response.data.data). Set this to false to return the response data (response.data) if you need yo access included for example.false
sortingArraySorting['id', '-name']
paginationObjectPagination{ page: 1, size: 10 } or { number: 1, pageSize: 10 }
filtersObjectFilters{ id: 4, name: 'test' }
resourceObjectAllows to set the resource type and id required when updating a resource.{ id: 1, type: 'posts' }
includeArrayPass an array of relations to include.['author', 'comments']
withCountArrayPass an array of countable relations to be included in the relationship meta.['comments']

Cutom parsers

You can add custom parsers to transform your requests to match the api('s) you're working with. Below a guide to add a custom parser.

  1. Create a parser file (/parsers/customParser.js)
  2. Extend the base parser and export:

    import BaseParser from './baseParser'
    
    class CustomParser extends BaseParser {
     // ...
    }
    
    export default CustomParser
  3. Add the parser to your nuxt config:

    nuxtFormHelper: {
      parsers: ['custom'],
      defaultParser: 'custom',
      customParsers: {
        custom: '@/parsers/customParser',
      }
    }
  4. ???
  5. PROFIT!!! $$$
0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago