Home > Back-end >  [Vue Warn]: Property "toggleFavorites" was accessed during render but is not defined on in
[Vue Warn]: Property "toggleFavorites" was accessed during render but is not defined on in

Time:07-28

I was creating some web app with vuejs2 CLI options API and I tried to create an event emitter but it keeps saying it has an error in the console and doesn't show up anything when the button which has the event emitter is clicked.

The error is shown in the console

1

And this was 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 with the toggleFavs method is the one I sent an event emitter with this method

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

The code on the main App.vue component is this:

<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>

where the method of the event 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 out guys I'm stuck.

here is the code:

CodePudding user response:

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

<script>
import FriendContact from './FriendContact.vue'
export default {
  components: {
    FriendContact
},
...
methods: {
...
</script>

Fixed example code

  • Related