Event Handling in Vue 3: Mastering User Interactions

Introduction to Vue.js

Vue.js is a JavaScript framework used to create interactive web interfaces. Vue is unique in its ability to enhance existing HTML, unlike other frameworks. We can also use Vue to write complete single-page applications (SPAs).

This enables the creation of fully Vue-managed tags, which can improve the developer experience and productivity when working with complex applications. It can also allow client-side routing and state management libraries if needed. Additionally, Vue takes a middle-ground approach to tools like client-side routing and state management.

Moreover, Vue also provides a step-by-step approach to writing markup. Like most frameworks, Vue allows us to create reusable tag blocks across components. In most cases, Vue components are written using a unique HTML template syntax.

Vue.js uses the virtual DOM, which is additionally utilized by other systems such as Respond, Ash, etc. The changes are not made to the DOM instead, a copy of the DOM is created which is displayed within the frame of JavaScript information structures.

Whenever changes are made, they are first applied to the JavaScript information structures, which are then compared to the initial information structures. Subsequently, the final changes are updated to the real DOM, visible to the client.

Installation

You need the following installations to work with Vue.js:

Node.js
Vue CLI

The command to install Vue using NPM is provided below:

npm install vue

Setting Up the Vue.js

With the Vue CLI, we can quickly design entire Vue projects. Ready to monitor our Vue-related conditions like Vue Router and Vuex using CLI.
First, run the take after the command:
“first-vue-proj-tutorial” will be the title of our project organizer.

vue create first-vue-proj-tutorial

Then based on our needs, select the features we want:

vue-cli-features

Next, you can include Vue Router in your project and examine the following code:

inlcuding-vue-router-in-your-project

At this point, you are ready to configure the remaining parts of your project.

configure-the-remaining-parts-of-your-project

The CLI tool will consequently make a purge venture for you. After the installation is complete, navigate to the project folder by running the cd command.

First, run our project to make sure everything is fine with the ‘npm run server’. You will see a page like this:

vue-js-app-dashboard

Don’t miss the opportunity to watch our captivating video on Vue.js!

Choose a User Interface Library

To define the website’s main design, look and feel, we can certainly write our own CSS and similar styles, but that can be quite complex. Common Vue UI frameworks include Vuetify, which provides a Vue UI system for material design, and Bootstrap-Vue, which combines Vue.js with Bootstrap for an efficient development experience.

Here is an example of a Bootstrap configuration:

To Get Started, Let’s Introduce the Prerequisites:

npn install bootstrap bootstrap-vue

After completing the installation, the next step is to modify the main.js file. In this file, we inform Vue to utilize our newly added Bootstrap and BootstrapVue dependencies.

Additionally, we’re including an IconsPlugin, which enables us to leverage Bootstrap icons throughout our entire project.

Making Components and Pages

Vue components are a key feature of Vue.js that allows you to design custom elements that may be reused in HTML. When a component is built, its name becomes a custom item that may be utilized in the newly formed Vue instance item.

Expanding the /src/ directory in the IDE Explorer window reveals a file titled App.vue.

Remove everything from the file before inserting the following code:

<template>
<div id="app"> <h1>{{message}}</h1>
<p> Learn more with the
<a
href="https://v3.vuejs.org/"
target="_blank"
rel="noopener"
>Vue Docs &amp; Resources</a>,
</p>
<button @click="doSomething">Say hello.</button>
</div>
</template>
<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<script>
export default {
data() {
return {
message: 'Welcome to Vue 3!';
},
},
methods: {
doSomething() {
alert('Hello!');
}
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e58;
margin-top: 60px;
}
a,button {
color: #4fc88d;
}
button {
background: none;
}
</style>

The result of the above code will look like this:

welcome-to-vue-3

A click event is generated when a button on the user interface is clicked. Depending on the functionality, clicking the button should trigger a specific action associated with the event. Event handling in Vue 3 enables us to listen to and respond to these events.

In Vue 3, event handlers utilize the v-on directive. We can use this directive to listen for DOM events like a click-and-fire JavaScript code. Event handlers in Vue.js support both inline handlers and method handlers.

1. Management of Inline Event Handling in Vue 3

The most effortless event-dealing approach in Vue 3 is to utilize inline event handlers.

 inlineEvent = "";

You can simplify the use of the v-on directive by directly specifying the event, such as v-on:click, to listen for a click event.

<template>
<button type="button"
class="text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
v-on:click="inlineEvent = 'YES'">Yes</button>
<button type="button"
class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
v-on:click="inlineEvent = 'NO'">No</button>
</template>

Fundamentally, inline event handlers are ideal for handling straightforward use cases where we need to execute a single statement in response to an event.

2. Method-based Event Handling in Vue 3

The foremost common approach to handling events in Vue.js 3 is to use strategies as event handlers.

countValue = null;

increaseCount() {
countValue.value++;
},

<button
type="button"
@click="increaseCount()"
class="text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
>
Count
</button>

In this context, we are associating the method increaseCount() with the click event. A method handler, in turn, receives the local DOM event object as an input parameter. To access the event within the method, you can modify the method handler’s signature as follows:

countValue = 0;

increaseCount(event) {
alert(event?.target?.tagName)
countValue.value++;
},

We can access properties from the event object and perform actions with them within the method as needed. This allows us to work with event-related data and perform specific tasks based on the event’s properties and values.

3. Calling Methods in Inline Event Handlers

Another interesting use case is directly calling event handlers from the DOM element. Using this function, we can supply custom method arguments instead of the normal DOM event.

Certainly, let’s consider the following example:

<button
type="button"
@click="increaseCount(5)"
class="text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
>
Count
</button>

countValue = 0;

increaseCount(number: Number) {
countValue.value = countValue?.value + number;
},

The number 5 is passed as an argument to the increaseCount() function. Then, within the increaseCount() function body, we can use it as an argument.

4. Event Argument with Inline Handlers in Vue.js

Accessing the original DOM event and passing a special method argument are two other use cases.

<button
type="button"
@click="increaseCount(5, $event)"
class="text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2"
>
count
</button>

countValue = 0;

increaseCount(number: Number, event: Event) {
console.log(event?.target?.tagName)
countValue.value = countValue?.value + number;
}

We can respond appropriately to DOM events by using the v-on directive in Vue 3. For simpler tasks, we can use inline handlers within the template itself. However, for more intricate logic and reasoning, we prefer to use method-based event handlers. Depending on the specific requirements, an application will often make use of both types of event handling.

coma

Conclusion

That concludes this part of the tutorial. In this section, we’ve successfully created a simple ‘Hello World’ application with Vue.js. Now, armed with this knowledge, we can proceed to create custom components and configure the application’s structure to meet the specific needs of our project.

Vue.js proves to be a valuable resource for developing progressive web applications (PWAs). It’s essential to note that comprehensive support and assistance are readily available for PWAs, ensuring their stability and enabling the removal of restrictions on both applications and websites.

Additionally, it’s worth highlighting that Vue’s component-based architecture provides ample opportunities to seamlessly incorporate additional functionality into your application as needed.

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!