【问题标题】:Error in render: "TypeError: Cannot read property 'name' of undefined" (Vue)渲染错误:“TypeError:无法读取未定义的属性‘名称’”(Vue)
【发布时间】:2020-04-08 06:34:42
【问题描述】:

我刚刚学习了 vuejs 使用像 vuex 这样的状态管理。

我收到了这个错误

渲染错误:“TypeError:无法读取未定义的属性‘名称’”

当我像这样从服务器填充数据时:

authenticated:{
  created_at:"2019-12-13 16:04:47"
  email:"super@vetura.id"
  email_verified_at:"2019-12-13 16:04:47"
  employee:{
    accountNumber:null
    address:"JL.VETERAN UTARA LR.124 NO.1"
    baseSalary:"10000000.000000"
    birthDate:"1987-09-14"
    birthPlace:"Ujung Pandang"
    category_id:null
    classification_id:null
    code:"000001"
    created_at:"2019-12-13 16:04:47"
    dateJoin:"2012-01-04"
    dateResign:null
    department_id:null
    division_id:null
    gender:null
    group_id:null
    height:172
    id:1
    idCardNumber:null
    kecamatan:null
    kelurahan:null
  }
  employee_id:1
  id:1
  role:"0"
  updated_at:"2019-12-15 14:22:26"
}

实际上,数据响应可以显示在模板上,当我尝试填充 authenticated.employee.name 时,控制台显示错误但可以显示数据。

TypeError: 无法读取未定义的属性“名称”

谁能帮帮我?

Error

对不起,我的英语不好。 ^_^

【问题讨论】:

    标签: php laravel vue.js vuejs2 vuex


    【解决方案1】:

    当你显示你的数据时,试试这样:

    authenticated.employee && authenticated.employee.name
    

    authenticated.employee ? authenticated.employee.name : ''
    

    这是因为在时刻 authenticated.employee 没有定义。

    随着那个错误将消失。

    您可以阅读more here 了解这一点。

    【讨论】:

    • 完美的兄弟。它工作兄弟.. 谢谢,我们必须先检查,我以前没想过,数据是否没有被 vue 完全加载??
    • 不客气,如果有帮助请标记为答案。
    【解决方案2】:

    可能是在来自服务器的响应中,员工为空。因为用户上没有员工 ID,或者具有该 ID 的员工不存在。

    如果以上不是问题。就我个人而言,我喜欢使用 _.get() 来处理“路径”中的某些内容可能为 null 并引发此错误的情况。

    let employeeName = _.get(response, 'employee.name');
    

    它的作用是在尝试名称之前检查员工是否不为空。如果employee 为null,则employeeName 将为null。这意味着您不必像这样链接一堆父检查:

    if (response.employee && response.employee.name) {
        let employeeName = response.employee.name;
    }
    

    https://lodash.com/docs/4.17.15#get

    【讨论】:

    • 是的,兄弟。谢谢,我们必须先检查一下,我以前没想过,vue 是否没有完全加载数据??
    猜你喜欢
    • 2018-10-01
    • 2019-12-01
    • 2021-02-17
    • 1970-01-01
    • 2018-07-14
    • 2021-03-21
    • 2021-08-18
    • 2020-09-17
    相关资源
    最近更新 更多