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 API | Composition API |
|---|---|
this.$bus | useBus |
this.$notify | useNotify |
this.$api, this.$fetch | useApi |
this.$auth | useAuth |
formValidatorMixin | useForm, useValidators, useServerErrors |
Flags
// nuxt.config.ts (defaults)
export default defineNuxtConfig({
we: {
bus: { optionsApi: true }, // this.$bus
notify: { optionsApi: true }, // this.$notify
form: { formValidatorMixin: true }, // formValidatorMixin auto-import
},
})2
3
4
5
6
7
8
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:
<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>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$notify
A thin wrapper around notivue's push:
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' })2
3
4
5
info | success | warn | error(title, text?, options?): with onlytitle, it is shown as the message; withtext,titlebecomes the title andtextthe message.optionsare passed to notivue (duration, ...).erroraccepts a string, anErroror an API error and shows the responsemessagewhen present.toast(options): notivue options plustype(infoby default); setmessageyourself.
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).
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 })2
3
$auth
A reactive object built from useAuth(): loggedIn, user, login, logout, fetchUser, setUserToken, getUserToken. In templates refs are already unwrapped:
<template>
<div v-if="$auth.loggedIn">
Hi, {{ $auth.user?.full_name }}
<v-btn @click="$auth.logout">Logout</v-btn>
</div>
</template>2
3
4
5
6
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.
<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>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Validators
Messages come from the validators.* i18n keys.
| Validator | Passes when |
|---|---|
validatorRequired | value is truthy |
validatorRequiredArray | value is an array (also empty) |
validatorRequiredArrayNotEmpty | value is an array with at least one item |
validatorNotNull | value is not null / undefined |
validatorRequiredNumber | value parses as an integer |
validatorEmail | empty or a valid email |
validatorPhone | empty 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.errorwhennotifyUntrackedis true; - scrolls to the first element matching
scroll.
| Option | Default | Description |
|---|---|---|
notifyUntracked | true | Show 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:
| Member | Description |
|---|---|
serverErrors | Proxy over the server errors; reading a key (in templates or code) marks it as shown. |
allServerErrors | All errors returned by the server. |
untrackedServerErrors | Computed: 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.