I'm new in vuejs, and I'm trying to fetch posts from a JSON file using the composition API, but I'm having a problem. After fetching post, too many texts are being displayed, which is what I don't want. I have tried to fix it using the following method:
<template>
<div class="max-w-md bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl m-6" v-for="post in post" :key="post.id">
<div class="md:flex">
<div class="md:flex-shrink-0" >
<img class="h-48 w-full object-cover md:h-full md:w-48" src="assets/store.jpg" alt="Man looking at item at a store">
<div class="p-8">
<div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">News</div>
<router-link :to="{name: 'Details', params:{id: post.id}}"><strong>{{post.title}}</strong></router-link>
<p class="mt-2 text-gray-500">{{snippet}}</p>
</div>
</div>
</div>
</template>
<script>
import { computed } from 'vue'
export default {
props:['post'],
setup(props) {
const snippet = computed(() => {
return props.post.body.substring(0,100) '...'
})
return{snippet}
}
}
</script>
The problem here is that when I run this piece of code, I get an error that says:
TypeError: Cannot read properties of undefined (reading 'substring')
And I don't even know how to go about this at the moment. Could someone please help?
CodePudding user response:
We can handle the undefined error by checking the properties value.
const snippet = computed(() => {
let body = ''
if (props.post && props.post.body){
body = props.post.body.substring(0,100) '...'
}
return body
})
CodePudding user response:
props.post.body
is undefined. It's better to debug why it's undefined. Nevertheless, if the
undefined` can be ignored you can use the following ES10 optional chaining operator.
props.post.body?.substring(0,100)