Why in Vue, when the array is initialized and the output is displayed, I get the error "Cannot read property of undefined"?
P粉642919823
P粉642919823 2023-08-28 23:38:03
0
1
438

我有两个vue文件,App.vue和一个组件UsersPage.vue。

UsersPage.vue:

 

和App.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?

P粉642919823
P粉642919823

reply all (1)
P粉087074897

In yourv-for, you usedusers.address.street.

When you pass[1, 2]tousersListand Vue parses the items viav-for, it tries to read each number ofaddress.street.

Because they are numbers, theiraddressisundefined. You will get the error you are encountering when you try to access any property ofundefined.

NOTE: If you want yourv-forto be able to parse items withoutaddresswithout throwing an error, you canusers .address.streetis replaced withusers.address?.street.
Documentation:nullish coalescing operator.


Also, you should not name your iteratorusers, as this may confuse you or other developers who need to modify this code as to whatusersis. . 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 itsaddress.streetproperty.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!