Alert: [Vue warning]: No valid handler found for event "click"

Currently, I am utilizing Vue 2 with class syntax and Typescript with TSX syntax. Despite encountering similar inquiries before, none of the proposed solutions seem to fit my specific situation.

My scenario involves creating an object array and displaying these objects as custom HTML elements, referred to as Chips. Each Chip has a boolean property called 'selected'.

The array, named registerCategory, consists of objects with a name (essentially text) and a boolean called

is_selected</code, initialized as false by default.</p>
<p>This is how I have rendered my Array:</p>
<pre><code>{this.registerCategory.map((field, index) => (
    <ZChip
    position={'start'}
    id = {'field-' + index}
    value={field}
    selected={this.registerCategory[index].is_selected}
    onClick={this.onCategorySelect(index)}
    >
      {this.$t(this.registerCategory[index].name)}
    </ZChip>
))}

The above code successfully displays all elements. However, my challenge lies in achieving selection upon click.

I have implemented a function in a separate file named registration.mixin.ts (also where the array is defined within a computed block):

methods: {
    onCategorySelect(index: number): void {
      this.registerCategory[index].is_selected = true;
    },
}

The intention was for this function to alter the is_selected as only the selected element's boolean value. Sadly, I encountered the following error:

[Vue warn]: Invalid handler for event "click": got undefined

If anyone could provide guidance, a solution, or alternative approach, it would be greatly appreciated. Thank you! :)

Answer №1

Have you already solved the problem? Unfortunately, I am unable to test it myself, but I strongly believe this solution will work, as it aligns with how indexes are managed in React (as far as I know):

  methods: {
    onCategorySelect(index: number): void {
      () => this.registerCategory[index].is_selected = true;
    },
  }

Answer №2

After closely examining my question and seeking guidance from my supervisor, I have identified two key issues in my code:

  1. The first problem was that I mistakenly placed the array within the computed object. It dawned on me that arrays with custom types cannot be defined in the data object. Additionally, any content within a computed block is immutable. To address this, I moved the array to the same class where the other components of my code were situated (specifically where the ZChip elements are). I acknowledge that there may be a more optimal location for initializing the array, but for now, this setup suffices.

  2. Another issue arose in the onClick function, where I needed to utilize an arrow function expression to invoke the corresponding function. The revised code snippet is as follows:

      {this.registerCategory.map((field, index) => (
        <ZidChip
        position="start"
        id={'field-' + index}
        value={field}
        selected={this.registerCategory[index].is_selected}
        onClick={() => this.onCategorySelect(index)}
        >
          {this.$t(this.registerCategory[index].name)}
        </ZidChip>
      ))}
    

The onCategorySelect method is defined as:

  private onCategorySelect(index: number): void {
    this.registerCategory[index].is_selected = !this.registerCategory[index].is_selected;
  }

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

Exploring the correct navigation of page objects through Protractor using TypeScript

I'm working on setting up a protractor test suite with TypeScript and running into an issue involving chaining of pageObjects for multiple pages. I haven't seen any examples that deal with this specific scenario. I've simplified the example ...

Mute Vue alerts during unit testing

I have been attempting to silence warnings in my tests by following the configuration provided here: https://vue-test-utils.vuejs.org/api/config.html#silent. The configuration is as follows: import { config } from '@vue/test-utils'; // setting ...

Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop. In order to perform this calculation, the input item.quantidade mus ...

Utilizing Vue with Firebase for managing hosting environment variables

Within my development environment, I currently have my firebase environment variables stored in a file named .env.development, with values like: VUE_APP_FB_API_KEY='abc123000123', VUE_APP_FB_AUTH_DOMAIN='site.firebaseapp.com', etc... ...

The term "primordials is not defined" is a common error

Whenever I attempt to run Gulp using the task runner, I am encountering this error message. I suspect it may be due to updating my npm project, but I'm unsure about how to resolve it. Should I try installing a different version of npm? >Failed to r ...

Does the Typescript compiler sometimes skip adding braces?

I am encountering a problem with compiling a specific section of code in my Angular2 project. public reloadRecords() { let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps; let data = new Array(this.recordsChartSteps ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

Creating a TypeScript function that utilizes generics to automatically infer the return type

How can I create a function with a generic argument that can return any type, and have the return type inferred from its usage? I attempted the following code: type Thing<T> = <U>(value: T) => U const shouldMakeStrings: Thing<string> ...

Using Vue.js's computed property to dynamically bind a class in v-bind

I am familiar with using v-bind:class when returning true or false from a computed function. I am curious to know if it is possible to use a computed property that matches the ID and value of a button being clicked. For example, clicking button 1 would al ...

Step up Vue.js with Phonegap without the need for any pre-existing templates or frameworks

Looking for guidance as a beginner in Vue.js and Phonegap. Seeking assistance to integrate Vue.js with Phonegap without relying on any templates or frameworks. A basic example of listing will suffice. Grateful for any help provided. Thank you! ...

[Protractor][Scroll] I need assistance with scrolling my webpage using a while loop. Could someone please help me troubleshoot the code?

When this function is called, it initiates scrolling and then pauses the browser for a 2-second period. scrollToElement(webElement: any) { browser.executeScript('window.scrollTo(0,400);').then(()=>{ console.log("sleepin ...

Utilizing Vue3 for Seamless State Persistence Upon Page Reloads

I recently switched to Vue3 and am exploring how to utilize vuex for state management. In my previous Vue2 setup, I would initialize the store upon app loading as shown below: // mains.js import VueRouter from "vue-router"; import Vuex from " ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Waiting for VueX to execute the mutation

Can VueX be used to create a method in the mounted() function that waits for a mutation in another component to be executed? Sometimes this mutation is triggered before and other times after, so I am curious if it's possible to await its execution af ...

Repeated parameters when making a second login request with axios and sending data in url-encoded format

Implementing token-based authentication and sending urlencoded data via axios. Passing the user and password to the axios function with all parameters set as per documentation. import axios from 'axios' const params = new URLSearchParams() param ...

Troubleshooting problem with displaying child component in Vue's nested routes

I am facing an issue with vue-router nested routes. https://router.vuejs.org/guide/essentials/nested-routes.html I created a parent route User and a child route UserQuotes, but the child route is not rendering. There are no error messages or warnings in ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Encountering an error when trying to add Vue Router to a pre-existing Vue.js project

Encountered npm error code ERESOLVE which led to the inability to resolve dependency tree. The error occurred while trying to resolve the dependencies for "[email protected]". It was found that "[email protected]" was present in the vue node_modu ...

Error message: Property is not found in the $rootScope object in AngularJS

Encountering an issue while attempting to assign a value to the rootscope in Typescript. class TestClass{ this.rootScope: ng.IRootScopeService; constructor($rootScope){ this.rootScope = $rootScope; } addValueToRoot=()=>{ ...

Prisma auto-generating types that were not declared in my code

When working with a many-to-many relationship between Post and Upload in Prisma, I encountered an issue where Prisma was assigning the type 'never' to upload.posts. This prevented me from querying the relationship I needed. It seems unclear why P ...