Annoying red errors appear in vue, for example, as shown in the figure below:
1.
2. Error in render: “TypeError: Cannot read properties of undefined (reading 'name’)”
Generally, such length reading errors are often very confusing. People are distressed, although vue renders normally,
why does such a problem occur?
- After the initialization of vue's life cycle phase begins, the life cycle begins,
- Define all the data in data to vm through Object.defineProperty, and there will be data on vm.
- Determine whether there is an el parameter to specify the scope of vue to control the HTML template, and continue to go down if there is, or wait for vm.$mount to call before going down.
- . . . . .
As mentioned above, if el is not mounted, the data will be rendered first, which will cause the above error.
Solution: 1. You can add v-if or ternary operation
to the data you want to render to judge.
<template>
<div>
<van-button type="primary" @click="LookImg">查看</van-button>
<van-popup v-model="show" closeable close-icon-position="top-left" :overlay="false" :style="{ height: '100%',width:'100%' }">
// 这里通过 v-if 进行判断,错误就可以解决了
<van-nav-bar v-if="Data.photos" :title="'剧照'+'('+Data.photos.length+')'"/>
// 这里通过 三元运算进行判断,错误就可以避免了
<input :value="Data.photos ? Data.photos.name : '' "/>
<van-row gutter="2" justify="center">
<van-col span="8" v-for="item in Data.photos" :key="item">
<van-image
class="photo-context"
height="100x"
width="100%"
:src="item"
/>
</van-col>
</van-row>
</van-popup>
</div>
</template>
<script>
export default {
props: {
Data: {
type: Object,
default () {
return {
}
}
}
},
data () {
return {
show:false
}
},
created () {
},
methods: {
LookImg(){
this.show = true
}
}
</script>
2. If the length is evaluated in the method, then we can do this:
if the value is assigned directly in the project, an error will occur, such as: "length of undefined" error
this.roleNumber = this.Data.role.length // 报错
Our solution is to make an if() judgment on it in the method , and then assign
// 可以对想要的属性或者是值的上一层进行if判断 比如,length的上一层进行判断
if(this.Data.role){
this.roleNumber = this.Data.role.length // 完美解决vue报错的问题
}