The "toggleFavorites" property was accessed during Render, but the property was undefined in the instance error
P粉511896716
P粉511896716 2024-01-29 12:03:55
0
1
475

I'm creating some web applications using the vuejs2 CLI options API and I'm trying to create an event emitter but it keeps saying there is an error in the console and nothing is displayed when a button with an event emitter is clicked.

Errors are displayed in the console

This is my code in the child component:

<template>
  <li>
    <h2>{{ name }} {{ friendIsFavorite ? "(Favorite)" : "" }}</h2>
    <button @click="toggleFavs">Toggle Favorite</button>
    <button @click="toggleDetails">Show Details</button>
    <ul v-if="detailsAreVisible">
      <li><strong>Phone:</strong> {{ phoneNumber }}</li>
      <li><strong>Email:</strong> {{ emailAddress }}</li>
    </ul>
  </li>
</template>

The first button using the toggleFavs method is the button I send the event emitter using this method

toggleFavs() {
      this.$emit("toggle-fav", this.id);
    },

The code on the main component of App.vue is as follows:

<template>
  <header> <h1>My Friends</h1></header>
  <ul>
    <friend-contact
      v-for="friend in friends"
      :key="friend.id"
      :id="friend.id"
      :name="friend.name"
      :phone-number="friend.phone"
      :email-address="friend.email"
      :is-favorite="friend.isFavorite"
      @toggle-fav="toggleFavorites"
    ></friend-contact>
  </ul>
</template>

The event method is defined as:

toggleFavorites() {
      // const targetedFriend = this.friends.find(
      //   (friend) => friend.id === friendId
      // );
      // console.log(targetedFriend);
      // targetedFriend.isFavorite = !targetedFriend.isFavorite;
      alert("This Works"); //just for demonstration but not working

Help me, I'm stuck.

This is the code:

P粉511896716
P粉511896716

reply all(1)
P粉277824378

There are two problems with your code. The first one was mentioned by @BoussadjraBrahim, which is a typo (mehtod instead of methods). The second problem is not importing the FriendContact component in App.vue and adding it to the components object.

sssccc

Fixed examplecode

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template