model
Updated on September 7, 2024Source codeTests
model
is a function that creates two-way data binding between a DOM element and your reactive reference.
Example
Usage
To create two-way binding, call the model
function, which requires two parameters: the element you're binding data to, and the model value—a reactive reference where model
can read and write the stored value.
model
also accepts an optional options
object as its final parameter.
import { model } from '@baleada/vue-features'
export function myCompositionFunction (...) {
model(element, modelValue[, options])
}
Here's a breakdown of the required parameters:
element
A reactive reference to the DOM element you're modeling data to.
Unlike other Baleada Features affordances, which let you pass an array of DOM elements as the first parameter, model
only accepts a reactive reference to a single DOM element.
modelValue
model
will read and write the two-way bound data.And here's a breakdown of the options
object:
key
value
event
input
model
should listen for on the DOM element to detect when new data has been entered by the end usertoValue
({ target: { value } }) => value
model
should store in the required.modelValue
reactive referenceHere's an example of how you could create two-way data binding on an HTML text input:
<!-- MyComponent.vue -->
<script setup>
import { ref } from 'vue'
import { model } from '@baleada/vue-features'
// Set up the DOM element ref and the value ref
const input = ref(null),
modelValue = ref('')
// Pass those reactive references to model
model(input, modelValue)
</script>
<template>
<!--
Attach the template ref to an element, and wait for
user input!
In this example, as soon as the 'input' event fires,
event.target.value will be stored in your `modelValue` reactive
reference, then `model` will set that value as the HTML
input's new value.
You can also programmatically assign a new value to your
`modelValue` reactive reference, and `model` will update the
HTML input's value automatically.
-->
<input ref="input" />
</template>
Here's an example of how you would use option
to customize model
's behavior to work with a checkbox
input:
<!-- MyComponent.vue -->
<script setup>
import { ref } from 'vue'
import { model } from '@baleada/vue-features'
// Set up the DOM element ref and the value ref
const input = ref(null),
modelValue = ref(false)
// Pass those reactive references to model
model(
input,
modelValue,
// Use options to make sure `model` is modelling the boolean `checked`
// property of the input, instead of grabbing the `value` property
// by default.
{ toValue: event => event.target.checked }
)
</script>
<template>
<!--
Attach the template ref to an element, and wait for
user input!
-->
<input type="checked" ref="input" />
</template>