Error in render: “TypeError: Cannot read property 'name' of undefined” (Vue)

前提是你 提交于 2020-04-11 17:12:34

问题


i just learn about vuejs using state management like vuex.

I got this error

Error in render: "TypeError: Cannot read property 'name' of undefined"

when i populate my data from server like this :

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

Actually, the data response can display on template, when i try to populate authenticated.employee.name the console show me an error but data can display.

TypeError: Cannot read property 'name' of undefined

Anyone can help me ?

Error

Sorry my english is bad. ^_^


回答1:


When you display your data try like this:

authenticated.employee && authenticated.employee.name

or

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

This is because in moment authenticated.employee is not defined.

With that error will disappear.

You can read more here about that.




回答2:


It could be that in the response from the server the employee is null. As in there was no employee id on the user or the employee with that id doesn't exist.

If the above is not the issue. Personally I like to use _.get() to handle a situation where there is the possibility of something in the 'path' being null and throwing this error.

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

What that does is handle checking if employee is not null before trying the name. employeeName would be null if employee is null. It means you don't have to chain a bunch of parent checks like this:

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

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



来源:https://stackoverflow.com/questions/59345740/error-in-render-typeerror-cannot-read-property-name-of-undefined-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!