Taha

How to Make Your Custom Vue Components Support v-model

Do you know that you can use v-model not only on native input elements (like <input>) but also on your custom input components?

If, for example, you have a custom component for selecting multiple values, you can use it like this:

<multi-value-input v-model="tags" />

Instead of this:

<multi-value-input :value="tags" @input="setTags" />

If you actually have such a component that accepts the value through :value prop and updates it through @input event, v-model will work out of the box!

So that's the trick! Your component should use value prop and @input event to support v-model.

Finally, if you want to use a different prop/event name and still support v-model, you have to use the model option on your component, like this:

model: {
  prop: 'checked', // instead of value
  event: 'changed' // instead of input
}
Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.