Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a welcome message app with Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create welcome-message
and select all the default options to create the project.
Create a Welcome Message App
To create the welcome message app, we write:
<template>
<form @submit.prevent="submit">
<div>
<label>first name</label>
<input v-model.trim="firstName" />
</div>
<div>
<label>last name</label>
<input v-model.trim="lastName" />
</div>
<button type="submit">submit</button>
</form>
{{ message }}
</template>
<script>
export default {
name: "App",
data() {
return {
firstName: "",
lastName: "",
message: "",
};
},
computed: {
formValid() {
const { firstName, lastName } = this;
return firstName.length > 0 && lastName.length > 0;
},
},
methods: {
submit() {
if (!this.formValid) {
return;
}
const { firstName, lastName } = this;
this.message = `hello, ${firstName} ${lastName}`;
},
},
};
</script>
We have the form with 2 input fields.
One is for entering the first name and one is for entering the last name.
To bind the input values to reactive properties, we have the v-model
directive.
The trim
modifier lets us trim the starting and trailing whitespace from the entered value.
To listen to the submit
event, we have the @submit
directive on the form.
The prevent
modifier lets us prevent server-side submission and do client-side submission.
In the component object, we have the data
method to return an object with the reactive properties and their initial values.
Next, we add the formValid
computed property to check if firstName
and lastName
have lengths bigger than 0.
Then finally, we add the submit
method that checks if formValid
is true
.
If it is, then we proceed to set the message
reactive property to the welcome message string.
Then message
is displayed below the form in the template.
Conclusion
We can create a welcome message app with Vue 3 and JavaScript.