Implement v-model on Vue components: compiled props, emit with model modifiers, named models and defineModel
Problem
v-model on a component looks like two-way binding, but Vue keeps data flow one way: the parent passes a prop down and listens for an event that carries the new value. The template compiler rewrites the directive into props, the runtime emit applies modifiers such as .trim, and since Vue 3.4 the defineModel() macro compiles to useModel(), a ref that reads the prop and emits on write. Build the three pieces.
// <NameInput v-model:first-name.trim="person.first" />
const props = vModelProps("first-name", ["trim"], () => person.first, (v) => (person.first = v));
// { "first-name": "Asha", "onUpdate:firstName": fn, "first-nameModifiers": { trim: true } }
// inside NameInput: const [first, modifiers] = defineModel("firstName")
first.value = " Ravi "; // emits update:firstName with "Ravi"; person.first becomes "Ravi"Ref. UR-1462 · © UIRound · uiround.com/questions/implement-v-model-on-vue-components-compiled-props-emit-with-model-modifiers-named-models-and-definemodel
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 4
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1
v-model:title.is only sugar for three props:trim="x" title,onUpdate:titleandtitleModifiers: { trim: true }. The default model usesmodelValueandmodelModifiers. The event name is camelized; the prop and modifier keys keep the argument as written.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.