개발/중거거래사이트 클론
[트러블 슈팅] Cannot read properties of undefined (reading 'userId')
coffee.
2024. 2. 23. 15:03
axios로 json을 받아와서 v-text로 받아온 값을 출력하는 데 생긴 문제입니다.
<template>
<div class="box">
<div class="images">
<div v-for="(photo,index) in item.photos" :key="index">
<img :src="`http://localhost:8080/images/${photo}`" class="image" />
</div>
</div>
<hr/>
<div class="profile">
<div class="user">
<div class="photo" >
<img :src="`http://localhost:8080/images/${item?.publisher?.profile}`" />
</div>
<div>
<span> {{ item.publisher.userId }} </span>
</div>
</div>
<div>
</div>
</div>
<hr/>
<div>
<h2>{{ item.title }}</h2>
<h3>{{ item.price }}</h3>
<p>
{{ item.content }}
</p>
</div>
</div>
</template>
<script>
export default{
data(){
return{
item:{},
user:{}
}
},
mounted(){
this.$axios.get(`http://localhost:8080/item/${this.$router.currentRoute._value.params.id}`)
.then((response)=>{
this.item=response.data;
console.log(this.item.publisher.userId);
});
},
}
</script>
제 생각에는 mount단계에서 item.publisher 라는 배열의 값이 undefined가 되면서 예외를 발생시키는 것이 원인입니다.
해결
해결책에는 두가지가 있습니다.
첫번째
data(){
return{
item:{
publisher:{
userId:""
}
},
user:{}
}
},
사용하고자 하는 배열의 원소를 직접 지정하는 것 입니다.
두번째
<span> {{ item?.publisher?.userId }} </span>