Vue 3 — v-model Modifiers and Components

Image for post
Image for post
Photo by Blaz Erzetic on Unsplash

Vue 3 is in beta and it’s subject to change.

Vue 3 is the up and coming version of Vue front end framework.

It builds on the popularity and ease of use of Vue 2.

In this article, we’ll look at how to use the Vue 3 v-model directive and create simple Vue 3 components.

Select Options

Select option values can be objects.

For instance, we can write:

to create a select dropdown that has option values bound to objects.

:value accepts an object.

So when we select a value, we’ll see that selected would also be an object.

This is because we set v-model ‘s value to selected .

v-model Modifiers

v-model can take various modifiers.

.lazy

The .lazy modifier makes v-model sync with the Vue instance state after each change event.

By default, v-model syncs with the state after each input event is emitted.

We can use that by writing:

.number

The .number modifier lets us convert whatever is entered to a number automatically.

For instance, we can write:

to convert numApples to a number automatically.

By default, an HTML input’s value is always a string, so this is a useful shorthand.

If the value can’t be parsed with parseFloat , then the original value is returned.

.trim

The .trim modifier automatically trims whitespace from user inputs.

We can use it by writing:

v-model with Components

v-model can be used with components as long as it emits an input event and takes in a value prop to populate the form control’s value.

This lets us make custom form control components easily.

Components Basics

We can create Vue components with the app.component method.

For example, we can write:

to create a component and then use it in our app.

We called app.component to with the component name as the first argument.

We called our component 'button-counter' .

The 2nd argument has the component object with the template and logic.

data returns the initial state object.

And template has the template string with the elements we want to display.

Inside it, we increment the count when a button is clicked and display the count .

Then we use the button-counter component in our app by adding the HTML for it.

Now we should see the increment button and the count value update as we click it.

Conclusion

v-model works with select options and components.

We can create simple components with the app.component method.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store