Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
How do I fix substring not working in vue.js 3?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
}) 
about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!