In this article, I’ll share with you the solutions I’ve found to a small issue I’ve encountered: using form input elements and the v-model attribute, in scoped slots.

_Also available _in french

Scoped slots and v-model

VueJS provides a pretty useful feature to make your code DRY ( Don’t repeat yourself): slots. If you are not aware of what slots are, I’ll give you an example. Dialog box is a good one. A dialog box always behaves the same way. When you open it, it creates a view appearing above the current view. This new view usually has a title, content, and some buttons. And the content could be anything! Some raw text, a form, a picture, a combination of those things, some other things… In this case, would you develop a new dialog box for each sort of content? The answer better be “Hell no!”. And slots would be your tool for the job. You’d create the “frame” component, which would take care of displaying a view over the previous one, and use a slot for the content.

But you probably already know all of that. What this article will be about, is one particular case I’ve had to handle: input elements in slots. Form input elements is a very interesting case because VueJS provides a particular attribute for them: v-model. An input field using v-model will keep in sync the value displayed in it and the variable it is linked to in your JavaScript.

v-model can’t work that way

The example I’ll use for this article is a custom dynamic form. Let’s say we want to build a form with input elements like <input> and <textarea> (which are eligible for v-model). And with each of these control, we want to display a warning if it is empty. One option would be to create two new components based on <input> for one and <textarea> for the other, adding this new feature, and then use those two new components in a form. One better option would be to create only one new component, let’s call it FormElement, which would implement this new feature, and would have a slot for the form input element.

#slot #javascript #vuejs #web-development #v-model

Form input elements and v-model in VueJS slots
6.90 GEEK