Vue 3 — Component and Vue Instance

Image for post
Image for post
Photo by Erik-Jan Leusink 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 create components with Vue 3.

Components and Props

Props are attributes that we can add to components to pass data to them.

To create a component that takes a prop, we can write:

We have the name prop that takes a string and we display it.

We can use v-for to render multiple items and render a component for each.

For instance, we can write:

Since we aren’t passing a string prop, we need the v-bind directive to let us pass non-string values to our component.

The key prop is needed so that Vue 3 can track the items properly.

In the app.component call, we have the props property with a prop name that’s accepted by our component.

And we can get the name property from the object.

Vue 3 components resemble web component spec’s custom elements.

It also implements the slot API so that we can use slots to add different content to our components.

The Vue Instance

The Vue instance is the root of our app.

We create it with the createApp method.

For instance, we can write:

We have our data object we which we return in the data method.

Then we can use the a property in our template.

The Vue.createApp method returns the Vue instance.

It should contain the properties of the data object as properties.

If we have:

The console log should log true .

And if we change the value of vm.a :

Then the value of a in the template and the data object should both change to 2.

Image for post
Image for post
Photo by Jose Murillo on Unsplash

Conclusion

Components can take props so we can populate it with data dynamically from the outside.

The Vue instance is the root of a Vue app.

It contains the data which can be changed and the change will be reflected everywhere.

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