You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This macro can be used to declare a two-way binding prop that can be consumed via `v-model` from the parent component, and it can be declared and mutated like a ref. This will declare a prop with the same name and a corresponding `update:propName` event.
232
+
This macro can be used to declare a two-way binding prop that can be consumed via `v-model` from the parent component. Example usage is also discussed in the [Component `v-model`](/guide/components/v-model) guide.
233
233
234
-
If the first argument is a literial string, it will be used as the prop name; Otherwise the prop name will default to `"modelValue"`. In both cases, you can also pass an additional object which will be used as the prop's options.
234
+
Under the hood, this macro declares a model prop and a corresponding value update event. If the first argument is a literal string, it will be used as the prop name; Otherwise the prop name will default to `"modelValue"`. In both cases, you can also pass an additional object which can include the prop's options and the model ref's value transform options.
235
235
236
-
```vue
237
-
<script setup>
236
+
```js
237
+
// declares "modelValue" prop, consumed by parent via v-model
The options object can also specify an additional option, `local`. When set to `true`, the ref can be locally mutated even if the parent did not pass the matching `v-model`, essentially making the model optional.
258
+
To access modifiers used with the `v-model` directive, we can destructure the return value of `defineModel()` like this:
256
259
257
-
```ts
258
-
// local mutable model, can be mutated locally
259
-
// even if the parent did not pass the matching `v-model`.
Usually, we need to conditionally transform the value read from or synced back to the parent when a modifier is present. We can achieve this via the `get` and `set` transformer options:
270
+
271
+
```js
272
+
const [modelValue, modelModifiers] =defineModel({
273
+
// get() omitted as it is not needed here
274
+
set(value) {
275
+
if (modelModifiers.trim) {
276
+
returnvalue.trim()
277
+
}
278
+
return value
279
+
}
280
+
})
261
281
```
262
282
263
-
### Provide value type <supclass="vt-badge ts" /> {#provide-value-type}
283
+
### Usage with TypeScript <supclass="vt-badge ts" /> {#usage-with-typescript}
264
284
265
-
Like `defineProps` and `defineEmits`, `defineModel` can also receive a type argument to specify the type of the model value:
285
+
Like `defineProps` and `defineEmits`, `defineModel` can also receive type arguments to specify the types of the model value and the modifiers:
0 commit comments