我有两个vue文件,App.vue和一个组件UsersPage.vue。
UsersPage.vue:
- 姓名:{{user.name}}, 用户名: {{user.username}},邮编: {{user.address.street}}
和App.vue:
C'est La Vue
当我运行这个程序时,没有错误,并且输出仍然显示。However, when I change usersList to any array with any number of elements (e.g. usersList:[1,2]
), the data is still displayed in the correct format, but in the browser's console The following error occurs:
Uncaught TypeError: Cannot read properties of undefined (reading 'street') at UsersPage.vue:19:149 at renderList (runtime-core.esm-bundler.js:2894:22) at Proxy._sfc_render (UsersPage.vue:19:163) at renderComponentRoot (runtime-core.esm-bundler.js:902:44) at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5615:57) at ReactiveEffect.run (reactivity.esm-bundler.js:187:25) at instance.update (runtime-core.esm-bundler.js:5729:56) at setupRenderEffect (runtime-core.esm-bundler.js:5743:9) at mountComponent (runtime-core.esm-bundler.js:5525:9) at processComponent (runtime-core.esm-bundler.js:5483:17)
Why do I get this error, even though the data is rendered correctly and the address exists in https://jsonplaceholder.typicode.com/users?
In your
v-for
, you usedusers.address.street
.When you pass
[1, 2]
tousersList
and Vue parses the items viav-for
, it tries to read each number ofaddress.street
.Because they are numbers, their
address
isundefined
. You will get the error you are encountering when you try to access any property ofundefined
.NOTE: If you want your
v-for
to be able to parse items withoutaddress
without throwing an error, you canusers .address.street
is replaced withusers.address?.street
.Documentation:nullish coalescing operator.
Also, you should not name your iterator
users
, as this may confuse you or other developers who need to modify this code as to whatusers
is. . You should name ituser
(for example:v-for="user in usersList" :key="user.id"
).But that doesn't change the fact that when it's a number, you can't access its
address.street
property.