You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2 Options API事件发射器报错:toggleFavorites未定义求助

问题解决

1. 核心错误:toggleFavorites 未定义

控制台提示的「Property "toggleFavorites" was accessed during render but is not defined on instance」,是因为在Vue 2 Options API中,你没有把toggleFavorites方法放到methods选项里。Vue实例只会识别methods对象内的方法。

修改App.vue的脚本部分,将方法放入methods:

export default {
  // 保留你的data等其他选项
  methods: {
    toggleFavorites(friendId) {
      const targetedFriend = this.friends.find(friend => friend.id === friendId);
      if (targetedFriend) {
        targetedFriend.isFavorite = !targetedFriend.isFavorite;
      }
      // alert("This Works");
    }
  }
}

2. 子组件模板的friendIsFavorite未定义问题

子组件模板中使用了friendIsFavorite,但你通过props接收的是is-favorite(对应Props中的驼峰式isFavorite),所以模板里应该直接用isFavorite:

<template>
  <li>
    <h2>{{ name }} {{ isFavorite ? "(Favorite)" : "" }}</h2>
    <!-- 其他按钮、列表代码不变 -->
  </li>
</template>

同时确保子组件的props定义正确:

export default {
  props: ['id', 'name', 'phoneNumber', 'emailAddress', 'isFavorite'],
  // 保留你的data、methods等其他选项
}

3. 确保事件传参正确

子组件toggleFavs方法已经通过this.$emit("toggle-fav", this.id)传递了好友ID,主组件的toggleFavorites方法需要接收这个参数才能定位到对应的好友,所以方法里要加上friendId参数,如第一步的代码所示。

完成以上修改后,点击「Toggle Favorite」按钮就能正常触发事件,修改好友的收藏状态了。

内容的提问来源于stack exchange,提问作者John Robi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 01:06:25