In the docs for vue’s v-model
modifiers, they give this example and there is a playground link as well.
<script setup>
const [model, modifiers] = defineModel({
set(value) {
if (modifiers.capitalize) {
return value.charAt(0).toUpperCase() + value.slice(1)
}
return value
}
})
</script>
<template>
<input type="text" v-model="model" />
</template>
This code can be edited so that the modifiers
variable is now foo
. What kind of pattern is this and how is this achievable (with pseudocode) since the value of const [model, foo] = ...
is in a different scope than foo.capitalize
?
<script setup>
const [model, foo] = defineModel({
// ^^^
set(value) {
if (foo.capitalize) {
// ^^^
return value.charAt(0).toUpperCase() + value.slice(1)
}
return value
}
})
</script>
<template>
<input type="text" v-model="model" />
</template>
2
Answers
As stated in comments, the fact that you can change the variable name and achieve the same results, is expected: there is nothing special to the name
model
— it is just a name.What can be confusing is that the
set
method reads from a variable that is only defined and assigned a value in the same expression thatset
method occurs in.But realise that this
set
method is not yet called whendefineModel
is called. Thefoo
(ormodel
) variable will be initialised by this overall expression, but theset
method is not called by this expression. This whole expression has already been evaluated and assigned tofoo
before theset
method is ever called.NB: It would have been a problem if the
defineModel
function would itself call theset
method of the given object. If that were the case,foo
would be undefined, and an error would be triggered when evaluatingfoo.capitalize
.As to the parsing of this code: the
foo
variable is declared, and its name is known for theset
function, and can be parsed without issue.Example
This principle is not specific for Vue. It is how things work in plain JavaScript.
Here is a simple JavaScript example, where
foo
is assigned without destructuring (which was an irrelevant aspect), andset
is called explicitly with someformat
function that is made available tofoo
:So, notice the order of the output that this snippet generates.
This usage of
defineModel
macro roughly translates to:defineModel
returns an array of 2 elements (tuple) that can be destructured, somodel
andmodifiers
variable names are arbitrary.modifiers
is accessed inside a computed at the time whenmodel.value
is changed, so this can’t causemodifiers is not defined
error.