VueJS: Event listeners like @keydown and @keyup, along with accessing elements using this.$refs, function properly with input fields but do not work

After successfully creating a basic speed typing game using vue.js, I encountered an issue when expanding the game to include multiple levels with longer sentences for users to type. This led me to realize the necessity of changing my <input> element to <md-textarea>, which is a vue.js component.

THE ISSUE:

The attributes that were functioning correctly with <input> are not behaving as expected with <md-textarea>:

  • @keyup="checkAnswer()"
  • @keydown="keymonitor"
  • @keydown.ctrl.86="noPaste" (to prevent paste via Ctrl+V)
  • @keydown.shift.45="noPaste" (to prevent paste via Shift+Insert)
  • ref="typeBox" (enables focusing on the element through this.$refs.typeBox[0].focus())

Please see the code snippets below for reference.

Could you assist me in debugging this issue? Any help would be greatly appreciated. Thank you.

NOTE: While an error may appear in the SO snippet feature, it does not exist in my development environment.

export default {
  name: 'game',

  data () {
    return {
      disabledKeys: ['ArrowLeft', 'Home']
    }
  },

  methods: {
    /**
     * prevents pasting via 'Ctrl + V' (@keydown.ctrl.86) and 'Shift + Insert' (@keydown.shift.45)
     */
    noPaste: function (event) {
      event.preventDefault()
    },

    /**
     * Monitors every single key input in the answer text box.
     *
     * Prevents using of disabled keys in the text input.
     */
    keymonitor: function (event) {
      if (this.disabledKeys.indexOf(event.key) >= 0) {
        event.preventDefault()
      }
    }, /*END keymonitor*/
    
    startTimer () {
      this.timer.id = setInterval(this.updateTimer, 1000)
      
      this.$nextTick(() => {
        this.$refs.typeBox[0].focus()
      })

      this.game.status = 'in progress'
    }, /*END startTimer*/
  } /* END methods */
} /* END export default */
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template>
  <md-input-container md-flex="100">
  
    <!-- this one is working -->
    <input id="typeBox" autocomplete="off" placeholder="Type here..." ref="typeBox" v-model="answer" @keydown="keymonitor" @keydown.ctrl.86="noPaste" @keydown.shift.45="noPaste"/>
    
    <!-- this one is not working -->
    <md-textarea id="typeBox" autocomplete="off" placeholder="Type here..." ref="typeBox" v-model="answer" @keydown="keymonitor" @keydown.ctrl.86="noPaste" @keydown.shift.45="noPaste"></md-textarea>
    
  </md-input-container>
</template>

Answer №1

To attach functions to the original events of a component's root element, you can utilize the .native modifier. For more details, refer to the guide here.

In your scenario, you can incorporate native event handlers into the <md-textarea> component in this manner:

<md-textarea 
  id="typeBox" 
  autocomplete="off" 
  placeholder="Type here..." 
  ref="typeBox" 
  v-model="answer" 
  @keydown.native="keymonitor" 
  @keydown.native.ctrl.86="noPaste" 
  @keydown.native.shift.45="noPaste"
></md-textarea>

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

What is causing the error "unable to access property 'map' of undefined" in my code?

Currently working on React + Redux and trying to implement a likes counter. However, encountering an error 'cannot read property 'map' of undefined'. Here is the code snippet for my Reducer: const initialState = { comments: [], ...

Using Node.js to parse XLSX files and generate JSON output

Recently, I came across an extremely well-documented node_module known as js-xlsx Curious: How can I convert xlsx to json format? This is the structure of the excel sheet: The desired json output should resemble the following: [ { "id": 1, "H ...

"Combining HTML, PHP, and JavaScript for Dynamic Web

Here is the PHP function that retrieves the visitor's profile image thumbnail: <?php echo voip_profile_image($visitorid,'thumb'); ?> The issue lies in the fact that $visitorid is stored in JavaScript under the sRemoteid parameter. Wi ...

How can I transfer an array from a servlet to HTML using jQuery?

As I parse an uploaded XML file with the dom, the generated string combines the hostname and osname values separated by a , delimiter. The variable s holds this string which is then sent back to HTML using the response.getWriter object obj. However, instea ...

Wait for a reply from one GET request before initiating the next one in node

When working with node, I am making two consecutive calls to an API. My goal is to ensure that the first GET request has completed before triggering the second one, using data from the response of the first call. To achieve this, I have experimented with ...

Is toastr functionality affected by bootstrap 5 updates?

I have recently updated my web app to use the latest version of Bootstrap 5 along with the toastr library. However, I have encountered issues with toastr options not functioning properly after the upgrade. Despite setting the values for toastr.options.time ...

Optimizing Wordpress by Efficiently Enqueueing Javascript

As a beginner with a WordPress website, I am aware that in order to execute scripts on a WordPress page, they need to be enqueued in the functions.php file. However, I'm unsure about the correct process for this. The specific JavaScript file I want t ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

Retrieve the value of the following object in a loop - Vue JS

I needed to verify whether a specific property of an object matches the property of the next object in an array of objects while looping through using a v-for loop. Here's an example JSON object: [ { Date: '21-July-2017', ...}, { Date: ...

Neglecting to refresh the content within the modal body

I am facing an issue with an empty modal on my webpage and an AJAX call that I am trying to execute as shown below (simplified for easier understanding). function fetchContent(x) { $.ajax({ type:"POST", url:"link", data:{id:"123"}, suc ...

Having trouble invoking an express route on mobile devices using the .click method

I'm experiencing a strange issue where my code works perfectly in Chrome browser but fails to function on my phone. Here's the snippet of code causing the problem: $('#plusSign').on('click', function() { var myLin ...

Guide to accessing and updating data in various tabs within a Google spreadsheet

I have two tabs named TAB A and TAB B. My goal is to iterate through TAB A and extract a set of values that I can then paste into TAB B. However, I encountered an error message saying, "Cannot read property 1, etc" function getValuesFromModal(form) { ...

Div containing scrollable content with overlaid child element

I am facing an issue with a scrollable div that contains a table, where I am trying to append a loader component as a child to cover the div when it's scrolled. However, the loader only covers the initial size of the div. Here is an example similar t ...

Guide to adding information to an .xml document

Currently, I am working on building a website for a school project, specifically an online shop. I am focusing on the shop section, where I need to store data such as name, price, image, and description in either a text file or XML format. Right now, the w ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

What is the best option: using a Javascript template or exploring another

Just starting out in web development. I want to include the same menu on every page of my new website, but I don't want to manually update it in each file whenever there's a change. Is there an easy template engine for JavaScript or another sol ...

Having trouble getting this.$set() to function properly with vue2.0 and Laravel integration

I'm currently attempting to store data in vue js and then display it on the view. This is my vue method: getVueItems: function(){ var vm = this; axios.get('/someuri').then(function(response) { vm.$set(this,'it ...

Utilizing Node.js and Eclipse to Transfer MongoDB Data to Browser

I am working on a project where I need to display data fetched from MongoDB using Node.js in a web browser. The data is stored in the 'docs' object and I want to pass it to an EJS file so that I can insert it into a table: var express = require( ...

Does using ng-if with a select and ng-options cause issues with ngModel?

Check out this plunker showcasing Angular's ngOptions feature: Angular Select Options Plunker I decided to spice things up by adding an ngIf directive to the initial select element: <div ng-if="1<2"> Color (null not allowed): <s ...