Implement v-model on Vue components: compiled props, emit with model modifiers, named models and defineModel

hardAbout 55 minutesUpdated CodingProvuev-modeldefine-modelemitcomponents
Not solved

Share this question

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

Stuck? Take a hint

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.

Every question and answer7 days, one payment