【问题标题】:Cannot read property 0 of undefined in Vue无法读取 Vue 中未定义的属性 0
【发布时间】:2018-11-13 17:57:29
【问题描述】:

所以我知道这个问题已被问过几次,但我似乎无法为我的案例找到解决方案。我正在使用 v-for 循环遍历对象数组,但是我也在访问每个对象的嵌套数组的数据。

注意* 最初我使用原始数据 getter 进行循环,但我切换到计算以查看它是否会对目前没有成功产生影响

这里是v-for

<tbody class="client-info table-bordered">
   <tr v-for="(user, index) in computedUsers"  :key="index" v-if="users.length > 0">
   <td class="text-capitalize">{{ user.user }}</td>
   <td>{{ user.email }}</td>
   <td>{{ user.role.name }}</td>// My issue is at this line
   <td class="text-center"><button class="btn btn-sm btn-secondary">Edit</button></td>
   </tr>
</tbody>

这是计算出来的属性

computed: {
    ...mapGetters(['users']),
     computedUsers() {
       if(this.users.length > 0 ) {
          const index = 0
            return this.users.map((user) =>({user: user.name, email: user.email, role: user.roles[index]}))
       }  
    }
  },

现在没有问题了非常感谢!

【问题讨论】:

  • 您几乎已经回答了自己的问题。当您最初加载页面时,users.length0,导致以下行无法运行。添加(提交)新用户后,它会尝试查找users.roles[index],其中index 出于某种原因被硬编码为0。那是你的错误。 user.roles 不是正确的数组。
  • 我的猜测是,在突变之后,它会在其中没有role 属性的用户记录之一上中断,因此是cannot read property 0 of undefined。确保您的每个新用户都有role 属性,更好的是它实际上至少分配了一个角色。
  • 我的问题是我用来改变users 的数组的response.data 不包括roles 数组。所以我实际上不得不修复我的后端代码。感谢您的帮助
  • 如果您找到了问题的解决方案,您应该回答您的问题,这样如果其他人找到此页面,他们就会得到答案。

标签: vue.js vuex


【解决方案1】:

为了解决我的问题,我需要在我的return response 中包含嵌套的数据数组。

当它在不包含 roles 数组的情况下运行 v-for 时,它显然不存在,因为我的返回响应仅发送 user 对象。

所以对于那些熟悉 Laravel 的人我改变了

return response($user, 200);

到这里

return response($user->load('roles'), 200);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 2019-01-30
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多