Attaching a button to a keypress event in Vue 3.0

I'm currently trying to figure out how to trigger a button when either clicked with the mouse or when a key is pressed. I'm having trouble understanding how components communicate with each other. How can I call the pressDown() function in the KeyButton component from its parent component, or is there a more efficient way to implement this functionality?

Below is my approach:

Container of the Button

<template>
  <key-button :message="'Msg'" :callback="pressKey" ></key-button>
</template>
<script setup>
import KeyButton from "./KeyButton.vue";
import {ref,onMounted} from "vue";
onMounted(()=>{
  addEventListener('keypress',(e)=>{
    //trigger button
  });
})
const pressKey = () => {
  //execute when the button is clicked
}
</script>

KeyButton Component

<template>
  <button class="button" :class="{'animate': active}" v-on="{mousedown:pressDown,animationend:triggerAnim}">{{props.message}}</button>
</template>

<script setup>
import {ref,defineProps} from 'vue';
const props = defineProps({
  message: String,
  callback: Function
})
const active = ref(false);
//Function to trigger button
const pressDown = ()=>{
  props.callback();
  triggerAnim();
}
const triggerAnim = ()=>{
  active.value = !active.value;
}

</script>

<style scoped>
button{
  display: flex;
  height: 5rem;
  width: 5rem;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
  color: white;
  border-color: deepskyblue;
  border-width: 0.15rem;
  border-radius: 50%;
  background-color: lightskyblue;
  margin-bottom: 1rem;
  margin-left: 2rem;
  outline: none !important;
}

.animate{
  animation: zoom 0.2s;
}

@keyframes zoom {
  0%{
    transform: scale(1);
  }
  10%{
    transform: scale(0.9);
  }
  100%{
    transform: scale(1);
  }
}
</style>

Answer №1

Avoid passing methods as props in vue to prevent creating interdependencies between components, enhancing reusability.

Instead of passing the method, emit an event from the KeyButton Component when a key is pressed and listen to it in the parent component using the following approach:

// KeyButton Component
<button @click="$emit('button-pressed')" />

// Parent
<KeyButton @button-pressed="pressKey" />

Answer №2

It is not recommended to pass callbacks as props between components in Vue. Instead, consider using the provide/inject pattern for sharing functions between components. You can learn more about this pattern here.

Alternatively, you can follow the approach suggested by Aside and utilize event handling in Vue. This involves emitting an event from the child component to the parent.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating Contact Form with PhoneGap API using JavaScript and HTML5

I am currently working on building a contact form using the PhoneGap API integrated with JavaScript and HTML5 for the form design. The contact form I am creating should allow me to add new contacts and search for existing ones. To achieve this, I have been ...

What is the standard error function used for jQuery promises?

Is there a way to establish a default error handling function for a jQuery promise? I am running a series of functions asynchronously, and if any of them encounter an error, I want the error to be reported. Currently, this is how I have to handle it: fun ...

Tips for adding a counter column to a jQuery DataTable

I'm working with a datatable that only shows records in the workflow step = "Waiting", the initial step in the process. My goal is to add a column displaying data like this: If record IDs are [95, 87, 65, 34, 12], the new column would show [5, 4, 3, ...

How to reference global Sass variables in a Sass module

My preferred method involves utilizing a global .scss file that houses all the foundational styles, such as primary color selections. Following this, I create separate modules for each React Component to maintain organization and reduce the need for import ...

How to lock a column in place using AngularJS

Attempting to adjust the position of a div in AngularJS (1.5) using the MacGyver library (). The id="reportOption" div remains fixed while the id="reports" div scrolls down. However, there is an issue where the id="reports" div shifts left when scrolling a ...

Refine radio button list based on input typed in text box

How can I filter my checkbox list based on letters typed into a textbox? The data for my checkbox list comes from a database. I attempted to do this using JavaScript, but it's not working. Is there a better way to achieve this functionality? <asp: ...

Is it possible to alter the hyperlink (href) dynamically according to the H2 content?

I am currently assisting a major affiliate website in dynamically replacing their links. They have expressed a desire to utilize the content of the H2 tags that follow their images with the class name wp-block-image. This is an example of the code: < ...

On smaller screens in portrait mode, CSS automatically incorporates margin adjustments

Here is the code I am working with: <html> <head> <style> body { margin: auto; width: 720px; } </style> </head> <body> <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ip ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

Scrolling the y-axis with a fixed height limit to prevent overflow

My current dilemma is a seemingly simple one: <div class="container"> <div class="a"></div> <div class="b"></div> <div class="c"></div> </div>​ Within the container, there are 3 divs: A and B ...

Tips for incorporating a page route with an HTML extension in Next.js

I'm facing a challenge in converting a non-Next.js page to Next.js while maintaining my SEO ranking. To preserve the route structure with HTML extensions and enhance visual appeal, I have outlined the folder structure below: https://i.sstatic.net/zO1 ...

Extracting HTML Data in Point of Interest (POI)

When creating a spreadsheet report using POI, I often come across html content with various tags like <p>, <b/>, &nbsp;, etc. Is there a way to parse these html tags in POI? Are there any functions in POI that can handle html content? Here ...

Error message: Cordova command not recognized following global installation

Attempting to set up Cordova on macOS Mojave, I executed the command npm i -g cordova for a global installation, which was successful. However, upon checking the version using cordova --version, I encountered the error "cordova: command not found". Furth ...

What is the best way to style an element with two classes in SCSS?

I've always understood that when targeting a div with two classes in SCSS, you should structure it like this: HTML: <div class="item active">...</div> SCSS: .item { &.active { /* add your code here */ } } But what about whe ...

Passing a JavaScript Object to an ASP.NET Handler

How can I send a JavaScript object to an ASP.NET Handler and extract its values? I have defined a complex type object as follows: function AccountObjCreate() { var AccountsView = {}; AccountsView.Username = null; AccountsView.Email = null; AccountsView.P ...

In Safari, there seems to be an issue where multiple URLs are not opening when clicked on from an anchor

Is there a way to open multiple URLs in Safari with just one click using window.open? I tried it, but only one URL opens in a new tab while the others do not. The version of Safari I am using is 11.0.1. onclick="window.open('URL1','_blank& ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

Create a rectangular container with text using CSS

Looking to achieve a square box design using CSS with specific dimensions? Want to insert text inside the square and ensure it is horizontally centered within the square? Check out this code snippet: #myid { width: 100px; height: 100px; ...

Finding a page element based on its title attribute in Selenium and Java

My goal is to locate and click on an image with the word "Collector" in its title. Below is the HTML code for the image and its link: <a href="javascript:*command*" title="Level III: KPI Collector RYG of D D/Testing - SYS"> <img src="*unusable l ...

The pagination functionality in the customized React Native list component is malfunctioning

In my customized list component known as TableList, there is a pagination functionality implemented. However, a peculiar behavior occurs when the user interacts with the pagination arrows. Upon clicking either the next or previous arrow for the first time ...