@gurso/v-ctrl v0.0.46
v-ctrl
Give info to handle form fields. Inspired by Angular Reative forms.
Install
npm install @gurso/v-ctrl
Use
In component
Composition API (setup)
import {vCtrl} from "@gurso/v-ctrl"
then use it to your component
option API
import {vCtrl} from "@gurso/v-ctrl"
then add it in directives property.
global
import { createApp } from "vue"
import App from "./App.vue"
import {vCtrl} from "@gurso/v-ctrl"
const app = createApp(App)
app.directive("ctrl", vCtrl)
app.mount("#app")
then use it to your app.
How it works
Class
You can use v-ctrl
directive on form fields html elements like input
, select
, textarea
You can just add the directive to an element :
<input v-ctrl />
Now the directive will automatically add/remove class
:
ctrl-valid
if the value is valid usingValidityState
APIctrl-invalid
if the value is not validctrl-touched
if user has focused the elementctrl-untouched
if user never focused the elementctrl-dirty
if user has changed valuectrl-pristine
if user has never changedctrl-unchanged
if the value is the same as use on 'initial'ctrl-changed
if the value has changedctrl-blank
if the value is 'empty'
Ctrl Object
this package provide ctrl
function wich return Ctrl
reactive object. The function take
as first optionnal argument the initial value of the element.
import { ctrl } from "@gurso/v-ctrl"
const fooCtrl = ctrl("bar")
then you can pass fooCtrl
to v-ctrl
directive:
<input v-ctrl="fooCtrl" />
fooCtrl contains properties which give info about element and value. The provided infos are the same than the previous describe class plus value and initial.
fooCtrl.value
the current value of the element (same as v-model)fooCtrl.initial
the value give in first argument toctrl
functionfooCtrl.valid
fooCtrl.invalid
fooCtrl.touched
fooCtrl.untouched
fooCtrl.dirty
fooCtrl.pristine
fooCtrl.unchanged
fooCtrl.changed
fooCtrl.blank
Validators
Some time, ValidityState
API is not enougth to handle our form.
So ctrl
function take as second argument and all next Validator
function.
Validator
function are function wich take the value as argument and return boolean.
if a validator return false
, the property valid
of the Ctrl
object will be false
.
import { ctrl } from "@gurso/v-ctrl"
function isPalindrome(v) {
return v === v.split("").reverse().join("")
}
const fooCtrl = ctrl("bar", isPalindrome)
Merge Ctrl
To merge multiple Ctrl
in one, you can the ctrls
function (with a 's' at the end).
The function take as arguments many Ctrl
object and return a Ctrls
reactive objet.
This object has the same property of Ctrl
object exept for value
replace by values
.
import { ctrl, ctrls } from "@gurso/v-ctrl"
const fooCtrl = ctrl()
const barCtrl = ctrl()
const mergeCtrls = ctrls(fooCtrl, barCtrl)
TODO
- warning: radio need
name
attribute (not need with v-model) - Modifiers: date ???
- test on components
- required/optional !!!