When the Enter key is pressed while in an input element within a child component, it triggers a method that was originally defined in the parent component as well

In my application, there is a parent component that allows users to select skills from a list of options. Additionally, there is a child component where users have the ability to add their own skill if it is not available in the parent component.

The challenge lies within the child component. When a user types a skill into the input field, an @keydown.enter event is triggered to add the input to an array. This functionality works correctly, but the issue arises when the keydown.enter event also invokes a method in the parent component that alters the state of the options element.

// parent component
<div class="card-body">
  <p class="card-subtitle font-weight-bold mb-1">Select Skills</p>

  <button 
    v-for="skill in skills" 
    :key="skill.id" 
    :class="[skill.state ? skillSelectedState : skillNotSelectedState]" 
    class="btn btn-sm m-2" @click="addSkill(skill)" 
    :value="skill.category">

      {{skill.skills}}

  </button>

  <clientInput></clientInput> // child component
</div>

<script>
import clientInput from './ClientSkillInput.vue'

export default {
  data() {
    return {

      skills: [], // fetching skills from an axios call
      selectedSkills: [],

    }
  }
}
methods: {

addSkill(skill) { // method being called

                if (!skill.state) {
                    this.selectedSkills.push(skill.skills);
                    skill.state = true;
                } else {
                    let position = this.selectedSkills.indexOf(skill.skills);
                    this.selectedSkills.splice(position, 1);
                    // skill.state = false;
                }
            },  

}



// child component

<template>
    <div class="form-group mt-2">
        <label class="d-block">Not what you're looking for?</label>
        <div class="customWraper">
            <div class="userSkillbox d-inline bg-secondary"> // using v-for to loop through userProvidedSkills and display user inputs
                Ruby on Rails
                <button class="userSkillboxBtn btn-sm border-0 text-white"> // remove the input item 
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <input v-model="userInput" type="text" class="d-inline border-0" placeholder="Type to add different skill" @Click="">
        </div>
        </div>
</template>

<script>
    export default {
        data() {
            return {
                isEditable: true,
                userInput: '',
                userProvidedSkills: [],
            }
        },

        methods: {
            addUserInput() {
                this.userProvidedSkills.push(this.userSkill);
                this.userSkill = '';
            }
        }

    }
</script>

Answer №1

It's not entirely clear where the keydown event is being added, but there are two possible solutions to consider:

1. Utilize an event modifier on the input element to prevent event propagation

<input @keydown.enter.stop

2. Implement the self event modifier on the parent component's button

<button 
v-for="skill in skills" 
@click.self="addSkill(skill)" 
:value="skill.category">

  {{skill.skills}}

For more detailed information on event modifiers, check out this resource

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

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

Dynamic Creation of a jQuery Selector

Dear, I'm facing an issue while trying to load data dynamically into a table using JSON format. The data is coming from a PHP file. However, despite my attempts, the table remains empty and no data is being displayed. function fetchTableData() { ...

Manipulating Hyperlinks outside the Angular JS applicationIn certain cases, Angular JS

This is my first attempt at creating a single page app. The app's content is contained within the page like a widget, functioning similar to pagination. In the header, I have links that are not related to the angular app. The link structure looks lik ...

Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "ReferenceError: $vAddress is not defined" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that add ...

Tips for interacting with Vue js buttons on JSP pages with Selenium WebDriver in Java

Having trouble locating elements rendered by vue.js within a JSP page. While I can find elements using xpath in normal JSP pages, those rendered by Vue.js remain elusive. For example, my JSP page includes: <div id="fileUploadDiv" style="display: flex; ...

Using JavaScript and PHP to dynamically update a field based on two input values within a row of a table

Currently in the process of developing a dynamic profit margin calculator for a personal project. Overview Data is retrieved from a database table using SQL and PHP After necessary validations, the data is dynamically displayed as rows in an HTML table ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text fil ...

javascript accessing an external variable inside ajax function

I have implemented dajaxice to fetch a json attribute that I want to make global. However, I am facing an issue where my global variable is always showing up as "undefined": var recent_id; $(function(){ recent_id = Dajaxice.ticker.get_home_timeline(ge ...

What is the best way to iterate through data within a view while showcasing information retrieved using AngularJS?

As I start my journey into learning AngularJS, I am looking for some guidance from those who have experience with it. Although I am proficient in JavaScript/jQuery, I am finding it challenging to grasp the fundamentals of AngularJS at the moment. My query ...

Top method for transferring the result of a function to descendant components in Vue

In my parent component, I have a data object named config structured like this: data() { return { config: { Groups: [ { name: "A", Types: [ { mask: 1234, name: ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

Tips for resolving the error message: React is not able to identify the `currentSlide` and `slideCount` prop on a DOM element

I recently implemented an image slider using "react-slick" in my next.js project. However, I encountered some warnings in the console related to the 'currentSlide' and 'slideCount' props on a DOM element. Warning: React does not recogni ...

What is the best way to send an event handler to a sibling component?

I am facing a situation where I have an eventHandler that needs to be handled by its sibling component. The <Brains /> component contains several properties (such as this.randomNumber = 555 inside the constructor) that are required for the proper fun ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...

Discovering the Data Structures within the d3.js Illustrations by the Talented Mike Bostock

Wondering how to decipher the structure of JSONs in examples by Mike Bostock, like this one (after being transformed using d3): http://bl.ocks.org/mbostock/3886208 I aim to replicate it with my own fabricated array of JSON objects without relying on load ...

I'm having trouble getting the app.locals function within a button to work on my EJS template. Can anyone help troub

Below is the content of my script named agents.js: var express = require('express'); var router = express.Router(); var app = express(); // Is it appropriate to call Express like this twice? router.get('/', function(req, res, next) { ...

Setting up multiple environments in CypressJs can be easily achieved by following these steps

I've been struggling to correctly set up my CypressJS environments for testing. Any assistance would be greatly appreciated. Within my index.html file, I have a CONFIG object in the <script> section. In production, this object is added by the M ...