@gurso/v-ctrl v0.0.46
v-ctrl
Give info to handle form fields. Inspired by Angular Reative forms.
Install
npm install @gurso/v-ctrlUse
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-validif the value is valid usingValidityStateAPIctrl-invalidif the value is not validctrl-touchedif user has focused the elementctrl-untouchedif user never focused the elementctrl-dirtyif user has changed valuectrl-pristineif user has never changedctrl-unchangedif the value is the same as use on 'initial'ctrl-changedif the value has changedctrl-blankif 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.valuethe current value of the element (same as v-model)fooCtrl.initialthe value give in first argument toctrlfunctionfooCtrl.validfooCtrl.invalidfooCtrl.touchedfooCtrl.untouchedfooCtrl.dirtyfooCtrl.pristinefooCtrl.unchangedfooCtrl.changedfooCtrl.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
nameattribute (not need with v-model) - Modifiers: date ???
- test on components
- required/optional !!!