Skip to content

Forms

TODO

Configuration

You can configure the module by adding the key fooms to the we object in your nuxt.config.js file.

js
we: {
  forms: false, // disable the module  (default true)
}

Simple Example

vue
<template>
  <v-form ref="form">  
    <we-select
      resource="provinces"
      v-model="model.province_id"
      :error-messages="serverErrors.province_id"
      :rules="rules.province_id"
      :label="$t('test.form.fields.province_id.label')"
    />
    <v-text-field
      v-model="model.string"
      :error-messages="serverErrors.string"
      :rules="rules.string"
      :label="$t('test.form.fields.string.label')"
    />
    <v-btn @click="save"> Save </v-btn>
  </v-form>
</template>

<script>

import { mergeDefaults, formValidatorMixin } from '@we/nuxt/forms'

const defaultValues = {
  province_id: null,
  number: 0,
}

export default {
  mixins: [formValidatorMixin],
  props: {
    value: {
      type: Object,
      required: false,
      default: undefined
    },
  },
  data: () => ({
    model: null,
  }),
  computed: {
    rules () {
      return {
        province_id: [this.validatorRequired],
        number: [],
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (val) {
        this.resetValidation()
        this.model = mergeDefaults(val, defaultValues)
      }
    }
  },
  methods: {
    resetValidation () {
      this.clearServerErrors()
      this.$refs.form?.resetValidation()
    },
    reset () {
      this.model = mergeDefaults({}, defaultValues)
      this.resetValidation()
    },
    async save () {
      if (!this.$refs.form.validate()) { return }

      try {
        const data = { ...this.model }
        const res = await this.$api.$post(`resource`, data)
        this.$emit('input', res)
      } catch (e) {
        this.checkServerErrors(e)
        // you can handle errors that are not 422
        this.$emit('error', e)
      }
    }
  }
}
</script>