Skip to content

Options API (legacy) ​

The Composition API composables are the recommended way to use the module. This page covers the globals and the mixin available to Options API components, mostly to keep older code working.

Options APIComposition API
this.$bususeBus
this.$notifyuseNotify
this.$api, this.$fetchuseApi
this.$authuseAuth
formValidatorMixinuseForm, useValidators, useServerErrors

Flags ​

ts
// nuxt.config.ts (defaults)
export default defineNuxtConfig({
  we: {
    bus: { optionsApi: true }, // this.$bus
    notify: { optionsApi: true }, // this.$notify
    form: { formValidatorMixin: true }, // formValidatorMixin auto-import
  },
})

Each flag only works when its feature is enabled (bus.enabled, notify.enabled, form.enabled). $api, $fetch and $auth are always provided.

$bus ​

The shared mitt instance, the same one used by useBus. Remove listeners in beforeUnmount:

vue
<script>
export default {
  mounted() {
    this.$bus.on('user:updated', this.onUserUpdated)
  },
  beforeUnmount() {
    this.$bus.off('user:updated', this.onUserUpdated)
  },
  methods: {
    onUserUpdated(user) {
      // ...
    },
    notifyUpdate(user) {
      this.$bus.emit('user:updated', user)
    },
  },
}
</script>

$notify ​

A thin wrapper around notivue's push:

js
this.$notify.success('Saved')
this.$notify.info('Title', 'Message')
this.$notify.warn('Careful', 'Check the data', { duration: 10000 })
this.$notify.error(error) // an API error or Error: its message is extracted
this.$notify.toast({ type: 'success', title: 'Done', message: 'Item created' })
  • info | success | warn | error(title, text?, options?): with only title, it is shown as the message; with text, title becomes the title and text the message. options are passed to notivue (duration, ...). error accepts a string, an Error or an API error and shows the response message when present.
  • toast(options): notivue options plus type (info by default); set message yourself.

The methods return nothing: there is no promise notification here, use useNotify for that.

$api and $fetch ​

this.$api is the useApi() instance, this.$fetch its underlying ofetch instance (API base URL and auth header already set).

js
const users = await this.$api.$get('users', { params: { active: 1 } })
const res = await this.$api.request({ method: 'post', url: 'users', data: this.model })
await this.$api.$postForm('documents', { file: this.file })

$auth ​

A reactive object built from useAuth(): loggedIn, user, login, logout, fetchUser, setUserToken, getUserToken. In templates refs are already unwrapped:

vue
<template>
  <div v-if="$auth.loggedIn">
    Hi, {{ $auth.user?.full_name }}
    <v-btn @click="$auth.logout">Logout</v-btn>
  </div>
</template>

formValidatorMixin ​

Deprecated

Use useForm and useValidators in new code.

The mixin is auto-imported (also available from #imports): no package import is needed. It adds validation rules and handling of Laravel 422 errors.

vue
<script>
const defaultValues = {
  name: null,
  email: null,
}

export default {
  mixins: [formValidatorMixin],
  props: {
    modelValue: { type: Object, default: undefined },
  },
  emits: ['update:modelValue', 'error'],
  data: () => ({
    model: { ...defaultValues },
    loading: false,
  }),
  computed: {
    rules() {
      return {
        name: [this.validatorRequired, this.validatorMax(255)],
        email: [this.validatorRequired, this.validatorEmail],
      }
    },
    isNew() {
      return !this.modelValue?.id
    },
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        this.clearServerErrors()
        this.$refs.form?.resetValidation()
        this.model = mergeDefaults(val, defaultValues)
      },
    },
  },
  methods: {
    async save() {
      const { valid } = await this.$refs.form.validate()
      if (!valid) { return }

      this.loading = true
      try {
        const method = this.isNew ? 'post' : 'put'
        const url = this.isNew ? 'users' : `users/${this.modelValue.id}`
        const res = await this.$api.request({ method, url, data: this.model })
        this.$emit('update:modelValue', res.data)
      } catch (e) {
        if (!this.checkServerErrors(e)) {
          this.$emit('error', e) // not a 422
        }
      }
      this.loading = false
    },
  },
}
</script>

<template>
  <v-form ref="form">
    <v-text-field
      v-model="model.name"
      :rules="rules.name"
      :error-messages="serverErrors.name"
      label="Name"
    />
    <v-text-field
      v-model="model.email"
      :rules="rules.email"
      :error-messages="serverErrors.email"
      label="Email"
    />
  </v-form>
</template>

Validators ​

Messages come from the validators.* i18n keys.

ValidatorPasses when
validatorRequiredvalue is truthy
validatorRequiredArrayvalue is an array (also empty)
validatorRequiredArrayNotEmptyvalue is an array with at least one item
validatorNotNullvalue is not null / undefined
validatorRequiredNumbervalue parses as an integer
validatorEmailempty or a valid email
validatorPhoneempty or digits only
validatorMin(length)empty or at least length characters
validatorMax(length, message?)at most length characters; message is an optional i18n key (default validators.maxLength, receives { length })
validatorMaxFileSize(bytes)empty or a file of at most bytes
validatorEquals(match, message)value === match, otherwise returns message as is

validatorMin, validatorMax, validatorMaxFileSize and validatorEquals are factories: call them in rules (this.validatorMax(255)).

Server errors ​

checkServerErrors(error, options?) clears the previous errors and, if error is a 422 response, fills serverErrors with the Laravel errors object and returns true (otherwise false). On the next tick it:

  • shows the errors with $notify.error when notifyUntracked is true;
  • scrolls to the first element matching scroll.
OptionDefaultDescription
notifyUntrackedtrueShow the errors in a notification.
scroll'.v-input.error--text'Selector of the element to scroll to; true uses the default selector, false disables scrolling.

Passing an options object replaces the defaults entirely, so { notifyUntracked: false } also disables scrolling. With Vuetify 3, inputs in error have the v-input--error class: pass { scroll: '.v-input--error', notifyUntracked: true } to scroll to them.

Other members:

MemberDescription
serverErrorsProxy over the server errors; reading a key (in templates or code) marks it as shown.
allServerErrorsAll errors returned by the server.
untrackedServerErrorsComputed: errors whose key was never read from serverErrors, i.e. not shown by any field.
clearServerErrors()Clears all the above.
checkUntrackedServerErrors(notify = true)Returns the error messages and, if notify, shows them with $notify.error.
decodeServerErrors(error)Fills the error objects from a 422 error without clearing, notifying or scrolling.

WARNING

Despite their names, checkUntrackedServerErrors and the notifyUntracked option currently notify all server errors, including the ones already shown next to a field. Use untrackedServerErrors if you need only the untracked ones.

Source Code ​